
\chapter{Typeclasses and functions of types\label{chap:Typeclasses-and-functions}}

\global\long\def\gunderline#1{\mathunderline{greenunder}{#1}}%
\global\long\def\bef{\forwardcompose}%
\global\long\def\bbnum#1{\custombb{#1}}%
\global\long\def\pplus{{\displaystyle }{+\negmedspace+}}%


\section{Motivation and first examples}

\subsection{Constraining type parameters}

The summation method, \lstinline!sum!, works for any collection of
numeric values:
\begin{lstlisting}
scala> Seq(1, 2, 3).sum
res0: Int = 6

scala> Seq(1.0, 2.0, 3.0).sum
res1: Double = 6.0
\end{lstlisting}
We can use \lstinline!sum! to compute the average of a sequence of
numbers,
\begin{lstlisting}
def avg(s: Seq[Double]): Double = s.sum / s.length
\end{lstlisting}
Can we generalize the averaging function \lstinline!avg! from \lstinline!Double!
to other numeric types, e.g.
\begin{lstlisting}
def avg[T](s: Seq[T]): T = ???
\end{lstlisting}
This code is impossible because averaging works only for certain types
\lstinline!T!, not for arbitrary types \lstinline!T! as implied
by the type signature above. We will be able to define \lstinline!avg[T]!
only if we constrain the type parameter \lstinline!T! to be a type
representing a suitable numeric value (e.g., \lstinline!Float!, \lstinline!Double!,
or \lstinline!BigDecimal!).

Another example of a similar situation is a function with type signature
$A\times F^{B}\rightarrow F^{A\times B}$, 
\begin{lstlisting}
def inject[F[_], A, B](a: A, f: F[B]): F[(A, B)] = f.map(b => (a, b))     // Must have `f.map`.
\end{lstlisting}
This function requires the type constructor \lstinline!F[_]! to have
a \lstinline!map! method, i.e., to be a functor. We can implement
\lstinline!inject! only if we constrain the parameter \lstinline!F!
to be a functor.

What would that constraint be like? Consider an ordinary function
with no type parameters, e.g.:

\begin{wrapfigure}{L}{0.28\columnwidth}%
\vspace{-0.85\baselineskip}
\begin{lstlisting}
def f(x: Int): Int = x + 1
\end{lstlisting}

\vspace{-0.95\baselineskip}
\end{wrapfigure}%

\noindent In this code, the syntax \lstinline!x: Int! constrains
the value of the argument \lstinline!x! to be integer. It is a type
error to apply \lstinline!f! to a non-integer argument. 

Using a similar syntax for \emph{type} \emph{parameters}, we would
write the type signatures for \lstinline!avg! and \lstinline!inject!
as
\begin{lstlisting}
def avg[T: Fractional](s: Seq[T]): T
def inject[F[_]: Functor, A, B](a: A, f: F[B]): F[(A, B)]
\end{lstlisting}
Scala uses the syntax \lstinline![T: Fractional]! to constrain the
type parameter \lstinline!T! to \textsf{``}fractional numeric\textsf{''} types. Similarly,
\lstinline![F[_]: Functor]! requires the type constructor \lstinline!F[_]!
to be a functor. Applying \lstinline!avg! or \lstinline!inject!
to types that do not obey those constraints will be a type error detected
at compile time.

In these examples, we are restricting a type parameter to a subset
of possible types, because only types from that subset have certain
properties that we need. A subset of types, together with the required
properties that those types must satisfy, is called a \textbf{typeclass}\index{typeclass}.
The syntax \lstinline![T: Fractional]! is a \textbf{typeclass constraint}\index{typeclass!constraint}
that forces the type \lstinline!T! to belong to the typeclass \lstinline!Fractional!. 

This chapter focuses on defining and using typeclasses and on understanding
their properties. We will see in detail how the syntax such as \lstinline![T: Fractional]!
is implemented and used.

\subsection{Functions of types and values}

The similarity between the type parameter \lstinline!T! and the argument
\lstinline!s! is clear in this type signature,
\begin{lstlisting}
def avg[T: Fractional](s: Seq[T]): T
\end{lstlisting}
\begin{comment}
def avg{[}T: Fractional{]}(s : Seq{[}T{]}): T = \{

val frac = implicitly{[}Fractional{[}T{]}{]}

frac.div(s.sum, frac.fromInt(s.length)) 

\}
\end{comment}
We can view \lstinline!avg! as a function that takes \emph{two} parameters
(a type \lstinline!T! and a value \lstinline!s!) and returns a value.
We can also view \lstinline!avg! as a function from a \emph{type}
\lstinline!T! to a \emph{value} of type \lstinline!Seq[T] => T!.
We may call functions of this kind \textbf{type-to-value}\index{type-to-value function}
functions (TVF). The syntax for TVFs supported in a future version
of Scala 3 will show this more clearly:
\begin{lstlisting}
val avg: [T] =>> Seq[T] => T = ...   // Scala 3 only.
\end{lstlisting}
To emphasize that \lstinline!avg! is a TVF, we may write the type
signature of \lstinline!avg! as
\begin{lstlisting}
def avg[T: Fractional]: Seq[T] => T // Inconvenient in practice! Use avg[T: Fractional](s: Seq[T]): T
\end{lstlisting}

A type constructor such as \lstinline!Seq[_]! can be seen as a \index{type-to-type function}\textbf{type-to-type}
function (TTF) because it takes a type \lstinline!T! and returns
a new type \lstinline!Seq[T]!.

Functions can map from values or from types and to values or to types,
as this table shows:
\begin{center}
\begin{tabular}{|c|c|c|}
\hline 
\textbf{\small{}functions...} & \textbf{\small{}from value} & \textbf{\small{}from type}\tabularnewline
\hline 
\hline 
\textbf{\small{}to value} & {\small{}(VVF)~ }\lstinline!def f(x:Int):Int! & {\small{}(TVF)~ }\lstinline!def pure[A]: A => List[A]!\tabularnewline
\hline 
\textbf{\small{}to type} & {\small{}(VTF)~ dependent type} & {\small{}(TTF)~ }\lstinline!type MyData[A] = Either[Int, A]!\tabularnewline
\hline 
\end{tabular}
\par\end{center}

We have already seen examples of VVFs, TVFs, and TTFs. Value-to-type
functions (VTFs) are known as \textbf{dependent} \textbf{types}\index{dependent type}
(or, more verbosely, as \textsf{``}value-dependent types\textsf{''}). An example in
Scala:

\begin{wrapfigure}{l}{0.36\columnwidth}%
\vspace{-0.75\baselineskip}
\begin{lstlisting}
val x = new { type T = Int }
val y: x.T = 123
\end{lstlisting}

\vspace{-0.75\baselineskip}
\end{wrapfigure}%

\noindent In this example, \lstinline!x.T! is a dependent type because
it is a type that depends on the \emph{value} \lstinline!x!. For
the value \lstinline!x! defined in this code, the expression \lstinline!x.T!
evaluates to the type \lstinline!Int!. 

We will not consider dependent types (VTFs) in this chapter because
typeclasses only require a combination of a TTF and a TVF.

\subsection{Partial functions of types and values}

We would like to define the function \lstinline!avg[T: Fractional]!
as a TVF that can be applied only to a subset of possible types \lstinline!T!.
This is similar to a \textbf{partial function}\index{partial function},
i.e., a function defined only for a subset of possible values of its
argument\textsf{'}s type. We may call such functions partial type-to-value
functions\index{partial type-to-value function} (PTVFs), to distinguish
them from partial value-to-value functions (PVVFs) we saw before.

In some situations, partial functions are safe to use. For instance,
the following partial function \lstinline!p!, 
\begin{lstlisting}
def p: Either[Int, String] => Int = { case Left(x) => x - 1 }
\end{lstlisting}
can be applied only to values of the form \lstinline!Left(...)!.
Applying \lstinline!p! to a value \lstinline!Right(...)! will cause
a run-time error. However, consider this code:

\begin{wrapfigure}{l}{0.45\columnwidth}%
\vspace{-1\baselineskip}
\begin{lstlisting}
val x = Seq(Left(1), Right("abc"), Left(2))

scala> x.filter(_.isLeft).map(p)
res0: Seq[Int] = List(0, 1)
\end{lstlisting}

\vspace{-1\baselineskip}
\end{wrapfigure}%

\noindent Although \lstinline!x.filter(_.isLeft)! has type \lstinline!Seq[Either[Int, String]]!,
all values in that sequence are guaranteed to be of type \lstinline!Left!.
So we know it is safe to apply the partial function \lstinline!p!
in \lstinline!.map(p)!. 

Although safe, this code is brittle: if the \lstinline!filter! operation
were moved to another place, we might by mistake write code equivalent
to \lstinline!x.map(p)!, causing a run-time exception. It is better
to refactor the code so that the compile-time type-checking guarantees
the safety of all operations at run time. For the example shown above,
the \lstinline!collect! method would make a partial function, such
as \lstinline!p!, safe to use:

\begin{wrapfigure}{l}{0.45\columnwidth}%
\vspace{-0.75\baselineskip}
\begin{lstlisting}
scala> x.collect { case Left(y) => y - 1 }
res1: Seq[Int] = List(0, 1)
\end{lstlisting}

\vspace{-0.75\baselineskip}
\end{wrapfigure}%

\noindent The \lstinline!collect! method is a \index{total function}\textbf{total}
function because it is defined for all values of its arguments and
does not throw exceptions. 

Total functions are safer to use than partial functions. The partial
function \lstinline!p! can be converted into a total function by
changing its type to \lstinline!Left[Int, String] => Int!. Another
example: applying \lstinline!head! to a \lstinline!List! is unsafe,
but the non-empty list type guarantees at compile time that the first
element exists:
\begin{lstlisting}
val xs: NonEmptyList[Int] = ...
val h = xs.head  // .head is a total function for a NonEmptyList.
\end{lstlisting}
In these cases, we achieve safety by making types more strictly constrained.
Similarly, partial type-to-value functions (PTVFs) become safe to
use if we impose suitable typeclass constraints on the type parameters.
Typeclasses can be viewed as a systematic way of safely managing PTVFs.

\section{Implementing typeclasses}

A typeclass constraint \lstinline![T: Fractional]! will generate
a compile-time error when a function such as \lstinline!avg[T]! is
applied to an incorrectly chosen type parameter \lstinline!T!. If
the Scala library did not already implement the \lstinline!Fractional!
typeclass, how could we reproduce that functionality?

\subsection{Creating a partial function at type level}

The code needs to specify that the type parameter must belong to a
certain subset of allowed types. To simplify the task, assume that
the allowed types are \lstinline!BigDecimal! and \lstinline!Double!.
One example of a type constraint is shown by unfunctors\index{unfunctor}
(see Section~\ref{subsec:Examples-of-non-functors}), which are type
constructors whose type parameters are restricted to specific types.
In this code:

\begin{wrapfigure}{l}{0.54\columnwidth}%
\vspace{-0.6\baselineskip}
\begin{lstlisting}
sealed trait Frac[A]              // Unfunctor.
final case class FracBD() extends Frac[BigDecimal]
final case class FracD()  extends Frac[Double]
\end{lstlisting}

\vspace{-0.75\baselineskip}
\end{wrapfigure}%

\noindent values of type \lstinline!Frac[A]! can be created only
if \lstinline!A = BigDecimal! or \lstinline!A = Double!. The keywords
\lstinline!sealed! and \lstinline!final! guarantee that no further
code could extend this definition and allow us to create a value of
type, say, \lstinline!Frac[String]! or \lstinline!Frac[Boolean]!.
Although the Scala compiler will not detect any errors in this code,

\begin{wrapfigure}{l}{0.32\columnwidth}%
\vspace{-0.75\baselineskip}
\begin{lstlisting}
type T = Frac[String]
type U = Frac[Boolean]
\end{lstlisting}

\vspace{-1\baselineskip}
\end{wrapfigure}%

\noindent we will never be able to create and use any values of types
\lstinline!T! or \lstinline!U!. In other words, the types \lstinline!Frac[String]!
and \lstinline!Frac[Boolean]! are \emph{void}\index{void type} types.
Trying to create and use values of these types will result in type
errors, as the following code shows:

\begin{wrapfigure}{l}{0.46\columnwidth}%
\vspace{-0.95\baselineskip}
\begin{lstlisting}[numbers=left]
def f[A]: Frac[A] = FracD()    // Type error.
val x: U = FracD()             // Type error.
val y: U = FracD().asInstanceOf[U]
y match { case FracD() => }    // Type error.
\end{lstlisting}

\vspace{-1.05\baselineskip}
\end{wrapfigure}%

\noindent In line~3, we disabled the type checker and forced the
Scala compiler to ignore the type error in the definition of \lstinline!y!.
However, line~4 shows that we are unable to use that value \lstinline!y!
in further computations.

The type \lstinline!Frac[A]! is non-void (i.e., has values) only
for $A$ belonging to the set \{\lstinline!BigDecimal!, \lstinline!Double!\}
\begin{comment}
$\{\text{BigDecimal},\text{Double}\}$
\end{comment}
{} of types. This set is called the \textbf{type domain}\index{type domain}
of the type function \lstinline!Frac!. We now need to define the
function \lstinline!avg[T]! with a type parameter $T$ constrained
to that type domain. 

The type constraint $T\negthickspace\in\,$\{\lstinline!BigDecimal!,
\lstinline!Double!\} is equivalent to the requirement that a value
of type $\text{Frac}^{T}$ should exist. So, we will implement the
type constraint if we include an \emph{additional argument} of type
$\text{Frac}^{T}$ into the type signature of \lstinline!avg!:
\begin{lstlisting}
def avg[T](s: Seq[T], frac: Frac[T]): T
\end{lstlisting}
The value \lstinline!frac:Frac[T]! is called a \index{typeclass!instance value}\textbf{typeclass
instance} value. Because that value needs to be passed to every call
of \lstinline!avg[T]!, we will be unable to use types \lstinline!T!
for which \lstinline!Frac[T]! is void (i.e., has no values). 

In this way, we implemented the typeclass constraint for the PTVF
\lstinline!avg[T]!. The main steps were:
\begin{enumerate}
\item Define a type constructor \lstinline!Frac[_]!.
\item Make sure values of type \lstinline!Frac[A]! exist only when \lstinline!A = BigDecimal!
or \lstinline!A = Double!.
\item Pass a value of type \lstinline!Frac[T]! to the function \lstinline!avg[T]!
as an additional argument.
\end{enumerate}
It is not necessary to define the type constructor \lstinline!Frac!
via an unfunctor. The type constructor \lstinline!Frac! is only needed
to define the type domain \{\lstinline!BigDecimal!, \lstinline!Double!\}.
We can use a simple case class instead:
\begin{lstlisting}
final case class Frac[T]()
val fracBD: Frac[BigDecimal] = Frac()
val fracD: Frac[Double] = Frac()
\end{lstlisting}

\noindent This code creates a type constructor \lstinline!Frac! and
makes values of type \lstinline!Frac[T]! available for chosen type
parameters \lstinline!T!. In this way, we implemented the required
type domain.

To write the code for \lstinline!avg[T]!, we need to be able to add
numeric values and to divide by an integer value. More precisely,
the body of \lstinline!avg[T]! needs access to two PTVFs that we
may call \lstinline!add! and \lstinline!intdiv!,
\begin{lstlisting}
def add[T](x: T, y: T): T
def intdiv[T](x: T, n: Int): T
\end{lstlisting}
Since \lstinline!avg[T]! now has an additional argument \lstinline!frac!,
we may use that argument to hold the required functions. So, we redefine
\lstinline!Frac! as a named tuple (case class) containing the functions
\lstinline!add! and \lstinline!intdiv!:
\begin{lstlisting}
final case class Frac[T](add: (T, T) => T, intdiv: (T, Int) => T)
\end{lstlisting}
Typeclass instances for \lstinline!BigDecimal! and \lstinline!Double!
are then created by the following code:
\begin{lstlisting}
val fracBD = Frac[BigDecimal]( (x, y) => x + y,  (x, n) => x / n )
val fracD = Frac[Double]( (x, y) => x + y,  (x, n) => x / n )
\end{lstlisting}
With these definitions, implementing \lstinline!avg[T]! becomes straightforward:
\begin{lstlisting}
def avg[T](s: Seq[T], frac: Frac[T]): T = {      // Assuming `s` is a non-empty sequence.
  val sum = s.reduce(frac.add)     // Here, `reduce` would fail on an empty sequence `s`.
  frac.intdiv(sum, s.length)       // Compute `sum/length`.
}
\end{lstlisting}
To use this function, we need to pass a typeclass instance corresponding
to the type \lstinline!T!:
\begin{lstlisting}
scala> avg(Seq(1.0, 2.0, 3.0), fracD) // It will be a type error to use fracBD instead of fracD here.
res0: Double = 2.0

scala> avg(Seq(BigDecimal(1.0), BigDecimal(2.0)), fracBD)
res1: BigDecimal = 1.5
\end{lstlisting}

This is a fully working implementation of the \lstinline!avg! function
with a \lstinline!Frac! typeclass constraint. We have achieved compile-time
safety since \lstinline!avg[T]! cannot be applied to values of unsupported
types \lstinline!T!. We have also achieved easy extensibility: To
implement another function as a PTVF with the same type domain, we
need to add an extra argument of type \lstinline!Frac[T]! to the
function. To add another supported type \lstinline!T! to the type
domain, we just write one more line of code similar to \lstinline!val fracD = ...!

An equivalent implementation of the \lstinline!Frac! typeclass via
a \lstinline!trait! with methods requires this code:

\begin{wrapfigure}{l}{0.6\columnwidth}%
\vspace{-0.65\baselineskip}
\begin{lstlisting}
trait Frac[T] {                 // Trait is not `sealed`.
  def add(x: T, y: T): T
  def intdiv(x: T, n: Int): T
}
val fracBD = new Frac[BigDecimal] {
  def add(x: BigDecimal, y: BigDecimal): BigDecimal = x + y
  def intdiv(x: BigDecimal, n: Int): BigDecimal = x / n
}
val fracD = new Frac[Double] {
  def add(x: Double, y: Double): Double = x + y
  def intdiv(x: Double, n: Int): Double = x / n
}
\end{lstlisting}

\vspace{-0.85\baselineskip}
\end{wrapfigure}%

\noindent The function \lstinline!avg[T]! will work unchanged with
this implementation of the \lstinline!Frac! typeclass.

The implementation via a \lstinline!trait! is significantly longer
than the code using a case class as shown previously. One advantage
of the longer code is the ability to combine different typeclasses
by \lstinline!trait! mixing. We will look at that in more detail
below. For now, we note that both implementations will require the
programmer to add a significant amount of new code:
\begin{itemize}
\item Calls to \lstinline!func[T](args)! need to be changed to \lstinline!func[T](args, ti)!
with typeclass instances \lstinline!ti!.
\item For each supported type \lstinline!T!, a corresponding typeclass
instance value needs to be created.
\item All those values need to be passed to all places in the code where
PTVFs are used.
\end{itemize}
The extra work can be reduced (and sometimes avoided) by using Scala\textsf{'}s
\textsf{``}implicit value\textsf{''} feature. 

\subsection{Scala\textsf{'}s \texttt{implicit} values}

An \textbf{implicit }\index{implicit value} declaration is a feature
of Scala that makes values automatically available to any function
that declares an \textsf{``}implicit argument\textsf{''} of the same type. Scala\textsf{'}s
syntax for implicit values is
\begin{lstlisting}
implicit val x: Int = 123
\end{lstlisting}
This declaration introduces an implicit value of type \lstinline!Int!
into the current scope. That value will be automatically passed as
an argument to any function declaring an argument of type \lstinline!Int!
as \lstinline!implicit!:
\begin{lstlisting}
def f(a: String)(implicit n: Int) = s"$a with $n"

scala> f("xyz")
res0: String = xyz with 123
\end{lstlisting}
We need to declare the arguments as \lstinline!implicit! in the function\textsf{'}s
type signature, and the implicit arguments must be in a \emph{separate}
\index{argument list}argument list.

The simplest useful function with an implicit argument is the identity
function. In the Scala library, this function is called \lstinline!implicitly!.
Compare its code with the code of the ordinary identity function:
\begin{lstlisting}
def implicitly[T](implicit t: T): T = t
def identity[T](t: T): T = t
\end{lstlisting}
What does \lstinline!implicitly[T]! do? Since its only argument is
declared as \lstinline!implicit!, we can simply write \lstinline!implicitly[T]!
with no arguments to apply that function. (The type parameter usually
needs to be specified.) If no implicit value of type \lstinline!T!
is available, a compile-time error will occur. If an implicit value
of type \lstinline!T! is available in the current scope, \lstinline!implicitly[T]!
will return that value:
\begin{lstlisting}
implicit val s: String = "qqq"

scala> implicitly[String]
res1: String = qqq
\end{lstlisting}

It is an error to declare more than one implicit value of the same
type in the same scope, because implicit arguments are specified by
type alone. The Scala compiler will not be able to set implicit arguments
of functions automatically when the function\textsf{'}s outer scope contains
more than one implicit value of a required type, as in this code:
\begin{lstlisting}
implicit val x: Int = 1
implicit val y: Int = 2

scala> implicitly[Int]
<console>:14: error: ambiguous implicit values:
 both value x of type => Int
 and value y of type => Int
 match expected type Int
       implicitly[Int]
                 ^
\end{lstlisting}
But it is not an error to declare several implicit arguments of the
\emph{same} type, e.g.
\begin{lstlisting}
def f(a: String)(implicit x: MyType, y: MyType)
implicit val z: MyType = ???

f("abc") // Same as f("abc")(z, z) since z is the unique implicit value of type MyType.
\end{lstlisting}
In the example above, the arguments \lstinline!x! and \lstinline!y!
will be set to the same value, \lstinline!z!. A compile-time error
will occur if no \lstinline!implicit! value of type \lstinline!MyType!
is visible in the current scope:
\begin{lstlisting}
scala> implicitly[MyType]
<console>:12: error: could not find implicit value for parameter e: MyType
       implicitly[MyType]
                 ^
\end{lstlisting}


\subsection{Implementing typeclasses by making instances \texttt{implicit} }

The idea is to declare typeclass instance values as \lstinline!implicit!.
Typeclass instance arguments of functions are also declared as \lstinline!implicit!.
As a result, typeclass instances will be passed to all PTVFs automatically
(as long as the appropriate implicits are visible in the scope of
the PTVFs). This makes typeclasses easier to use because instance
values need to be written out much less often.

The example with the \lstinline!Frac! typeclass is implemented using
implicit values like this:
\begin{lstlisting}
final case class Frac[T](add: (T, T) => T, intdiv: (T, Int) => T)
implicit val fracBD = Frac[BigDecimal]( (x, y) => x + y,  (x, n) => x / n )
implicit val fracD = Frac[Double]( (x, y) => x + y,  (x, n) => x / n )
\end{lstlisting}
To define the function \lstinline!avg[T]!, we declare an implicit
argument as a \lstinline!Frac! typeclass instance for \lstinline!T!:
\begin{lstlisting}
def avg[T](s: Seq[T])(implicit frac: Frac[T]): T = { // Assuming `s` is a non-empty sequence.
  val sum = s.reduce(frac.add)     // Here, `reduce` would fail on an empty sequence `s`.
  frac.intdiv(sum, s.length)       // Compute `sum/length`.
}
\end{lstlisting}
It is now easier to use the function \lstinline!avg! because the
typeclass instances are inserted automatically:
\begin{lstlisting}
scala> avg(Seq(1.0, 2.0, 3.0))
res0: Double = 2.0

scala> avg(Seq(BigDecimal(1.0), BigDecimal(2.0)))
res1: BigDecimal = 1.5
\end{lstlisting}

Scala supports the \textsf{``}type constraint\textsf{''} syntax for implicit typeclass
instance arguments: the code
\begin{lstlisting}
def f[A, B](args...)(implicit t1: Typeclass1[A], t2: Typeclass2[B])
\end{lstlisting}
is equivalent to the shorter code 
\begin{lstlisting}
def f[A: Typeclass1, B: Typeclass2](args...)
\end{lstlisting}
The shorter code omits the names (\lstinline!t1!, \lstinline!t2!)
of the typeclass instances. These values can be extracted via the
standard function \lstinline!implicitly! because all implicit arguments
are automatically made available as implicit values in the scope of
a function\textsf{'}s body. The code of \lstinline!avg[T]! can then be written
as
\begin{lstlisting}
def avg[T: Frac](s: Seq[T]): T = {
  val frac = implicitly[Frac[T]]
  val sum = s.reduce(frac.add)
  frac.intdiv(sum, s.length)
}
\end{lstlisting}

When an implicit argument is required, the Scala compiler will search
for implicit values of the required type in different places of the
code. If implicit values are declared in another module, they can
be made available by using an \lstinline!import! declaration. In
many cases, explicit \lstinline!import! declarations can be avoided.
One way to avoid them is to declare the required implicit values within
the \textbf{companion object}\index{companion object} of the typeclass
(i.e., the Scala \lstinline!object! with the same name as the type
constructor):
\begin{lstlisting}
final case class Frac[T](add: (T, T) => T, intdiv: (T, Int) => T)

object Frac {   // The companion object of `Frac[T]` creates some typeclass instances as `implicit`.
  implicit val fracBD = Frac[BigDecimal]( (x, y) => x + y,  (x, n) => x / n )
  implicit val fracD = Frac[Double]( (x, y) => x + y,  (x, n) => x / n )
}
\end{lstlisting}
Whenever a function needs an implicit value of type \lstinline!Frac[T]!
for a specific type \lstinline!T!, the Scala compiler will automatically
look within the companion object of \lstinline!Frac! (as well as
within the companion object of the type \lstinline!T!) for any instances
declared there. So, the programmer\textsf{'}s code will not need to \lstinline!import!
those typeclass instances explicitly even if the companion object
is in a different module:
\begin{lstlisting}
scala> avg(Seq(1.0, 2.0, 3.0))
res0: Double = 2.0
\end{lstlisting}


\subsection{Extension methods}

In Scala, function applications can use three kinds of syntax: 
\begin{enumerate}
\item The \textsf{``}function\textsf{''} syntax: arguments are to the right of the function
as in \lstinline!plus(x, y)! or \lstinline!plus(x)(y)!.
\item The \textsf{``}method\textsf{''} syntax: the first argument is to the left of the
function, and all other arguments (if any) are placed to the right
of the function, as in \lstinline!x.plus(y)! or \lstinline!xs.foldLeft(0)(updater)!.
\item The \textsf{``}infix method\textsf{''} syntax (only applies to functions with two
\emph{explicit} arguments): no dot character is used, as in \lstinline!x plus y!,
or in \lstinline!xs map {x => x + 1}!, or in \lstinline!Set(1,2,3) contains 1!.
\end{enumerate}
The last two syntax features are often used when writing chains of
function applications, such as \lstinline!xs.map(f).filter(g)!, because
that code is easier to read than \lstinline!filter(map(xs, f), g)!. 

The method syntax is available only for methods defined in a class.
A special feature of Scala allows us to add new functions with method
syntax to previously defined types. New functions added in this way
are called \index{extension methods}\textbf{extension methods}. 

Suppose we would like to convert a previously defined function, say
\begin{lstlisting}
def func(x: X, y: Y): Z = { ... }
\end{lstlisting}
into an extension method on the type \lstinline!X! with the syntax
\lstinline!x.func(y)!. To do that, we define a new helper \lstinline!class!
that has a method named \lstinline!func!. The class\textsf{'}s constructor
must be declared as an \lstinline!implicit! function having a \emph{single}
argument of type \lstinline!X!:
\begin{lstlisting}
implicit class FuncSyntax(x: X) {  def func(y: Y): Z = ... }
\end{lstlisting}
After this code, we can write the method syntax \lstinline!x.func(y)!
as well as the infix method syntax \lstinline!x func y!. The new
syntax will work because the compiler automatically rewrites \lstinline!x.func(y)!
into \lstinline!new FuncSyntax(x).func(y)!, creating a new temporary
value \lstinline!FuncSyntax(x)!. The method \lstinline!func! will
be available since it is defined in the class \lstinline!FuncSyntax!. 

As an example, let us define an extension method \lstinline!average!
for the type \lstinline!Seq[T]!. Both the type parameter \lstinline!T!
and its typeclass constraint can be written in the constructor of
the helper class:
\begin{lstlisting}
implicit class AvgSyntax[T: Frac](xs: Seq[T]) {
  def average: T = avg(xs) // Use a different name, `average`, to avoid name clash with `avg`.
}
\end{lstlisting}
We can now use the method \lstinline!average! on numeric sequences:
\begin{lstlisting}
scala> Seq(1.0, 2.0, 3.0).average
res0: Double = 2.0
\end{lstlisting}
The Scala compiler automatically rewrites the syntax \lstinline!Seq(1.0, 2.0, 3.0).average!
as the expression
\begin{lstlisting}
new AvgSyntax(Seq(1.0, 2.0, 3.0))(implicitly[Frac[Double]]).average
\end{lstlisting}
In this way, the method \lstinline!average! is actually invoked on
a temporarily created value of type \lstinline!AvgSyntax!. These
values will be created automatically because the class constructor
of \lstinline!AvgSyntax! is declared as \lstinline!implicit!. Since
the constructor of \lstinline!AvgSyntax! includes the typeclass constraint
\lstinline![T: Frac]!, we will not be able to create values of type
\lstinline!AvgSyntax[T]! for types \lstinline!T! not in the type
domain of \lstinline!Frac!.

This example illustrates the convenience of implementing PTVFs as
extension methods. An extension method is defined only once but automatically
becomes available for all types in the domain of the typeclass. Because
of the typeclass constraint, the new method will be available \emph{only}
on values of supported types.

This convenience comes at a cost: helper classes such as \lstinline!AvgSyntax!
need to be explicitly imported into every scope where extension methods
are used, with a declaration like this:
\begin{lstlisting}
import some.library.having.a.longwinded.packagename.AvgSyntax
\end{lstlisting}
If the helper class is defined in some library, the programmer will
have to look at the library\textsf{'}s source code to determine the full name
of the helper class that needs to be imported.

\subsection{Solved examples: Implementing typeclasses in practice\index{solved examples}}

We will now look at some practical examples of programming tasks implemented
via typeclasses.

\subsubsection{Example \label{subsec:tc-Example-metadata-extractors}\ref{subsec:tc-Example-metadata-extractors}
(metadata extractors)}

An application needs to work with data structures implemented in various
external libraries. All those data structures are case classes containing
certain metadata: \textsf{``}name\textsf{''} (a \lstinline!String!) and \textsf{``}count\textsf{''}
(a \lstinline!Long! integer). However, the specific data structures
define the metadata differently, each in its own way:
\begin{lstlisting}
final case class Data1(p: String, q: String, r: Long) // "name" = p, "count" = r
final case class Data2(s: String, c: Long, x: Int)    // "name" = s, "count" = c
final case class Data3(x: Int, y: Long, z: String)    // "name" = z, "count" = x * y
\end{lstlisting}
The task is to implement two functions, \lstinline!getName[T]! and
\lstinline!getCount[T]!, for extracting the metadata out of the data
structures of type \lstinline!T!, where \lstinline!T! is one of
\lstinline!Data1!, \lstinline!Data2!, \lstinline!Data3!. Type signatures
and sample tests:
\begin{lstlisting}
def getName[T: HasMetadata](t: T): String = ???
def getCount[T: HasMetadata](t: T): Long = ???

scala> getName(Data2("abc", 123, 0))
res0: String = abc

scala> getCount(Data3(10, 20, "x"))
res1: Long = 200
\end{lstlisting}


\subparagraph{Solution}

We will implement a typeclass \lstinline!HasMetadata! and declare
instances only for \lstinline!Data1!, \lstinline!Data2!, and \lstinline!Data3!.
The code for extracting the metadata will be contained within the
typeclass instances. Since the metadata extractors have types \lstinline!T => String!
and \lstinline!T => Long!, a simple solution is to define the typeclass
as a \lstinline!case class! containing these two functions:
\begin{lstlisting}
final case class HasMetadata[T](getName: T => String, getCount: T => Long)
\end{lstlisting}
The required typeclass instances are declared as implicit values within
the companion object:
\begin{lstlisting}
object HasMetadata {    // Extract metadata from each type as appropriate.
  implicit val data1 = HasMetadata[Data1](_.p, _.r)
  implicit val data2 = HasMetadata[Data2](_.s, _.c)
  implicit val data3 = HasMetadata[Data3](_.z, data3 => data3.x * data3.y)
}
\end{lstlisting}
Now we can define \lstinline!getName! and \lstinline!getCount! as
PTVFs with typeclass constraints. First, let us write the code using
an implicit argument to pass the typeclass instance:
\begin{lstlisting}
def getName[T](t: T)(implicit ti: HasMetadata[T]): String = ti.getName(t)
def getCount[T](t: T)(implicit ti: HasMetadata[T]): Long = ti.getCount(t)
\end{lstlisting}
Or we could use the typeclass constraint syntax, replacing \lstinline!ti!
by calls to \lstinline!implicitly[...]!:
\begin{lstlisting}
def getName[T: HasMetadata](t: T): String = implicitly[HasMetadata[T]].getName(t)
def getCount[T: HasMetadata](t: T): Long = implicitly[HasMetadata[T]].getCount(t)
\end{lstlisting}

This code defines PTVFs \lstinline!getName! and \lstinline!getCount!
with the type domain that contains the three types \lstinline!Data1!,
\lstinline!Data2!, \lstinline!Data3!. In order to add a new type,
say \lstinline!Data4!, to the type domain, we will need to declare
a new typeclass instance as an implicit value of type \lstinline!HasMetadata[Data4]!.
New implicit values can be defined anywhere in the code, not necessarily
within the companion object \lstinline!HasMetadata!. To avoid extra
\lstinline!import! statements, the implicit value may be defined
within the companion object of \lstinline!Data4!:
\begin{lstlisting}
final case class Data4(x: Int, message: String)
object Data4 {   // Add Data4 to the type domain of HasMetadata:
  implicit val data4 = HasMetadata[Data4](_.message, _.x.toLong)
}

scala> getName(Data4(1, "abc"))
res2: String = abc
\end{lstlisting}

For convenience, let us declare the metadata extractors as extension
methods:
\begin{lstlisting}
implicit class ExtractorsSyntax[T: HasMetadata](t: T) {
  def name: String = getName(t)
  def count: Long = getCount(t)
}
\end{lstlisting}
With this definition, we can write:

\begin{wrapfigure}{l}{0.34\columnwidth}%
\vspace{-0.85\baselineskip}
\begin{lstlisting}
scala> Data2("abc", 123, 0).name
res3: String = "abc"

scala> Data3(10, 20, "x").count
res4: Long = 200
\end{lstlisting}

\vspace{-0.95\baselineskip}
\end{wrapfigure}%

\noindent The code looks as if the new methods \lstinline!name! and
\lstinline!count! became available for each of the supported data
types. It is important that the new methods were added \emph{without}
any changes to the implementations of \lstinline!Data1!, \lstinline!Data2!,
or \lstinline!Data3!. Those implementations may reside in external
libraries whose code we do not need to modify. The typeclass pattern
enables us to to add externally defined types to a type domain whenever
necessary, and to implement new PTVFs for them.

\subsubsection{Example \label{subsec:tc-Example-observability}\ref{subsec:tc-Example-observability}
(counters)}

A certain application needs to count the number of files processed
and to send this number to external observability services. The functionality
of a counter is provided by an external library as a special class
\lstinline!Counter! with an \lstinline!inc! method that increments
the counter. To test the code, we want to be able to pass a test-only
counter provided by another library as a type \lstinline!TestCounter!
with an \lstinline!incr! method. The task is to implement a function
\lstinline!bump[C]()!, where \lstinline!C! is a type constrained
to be one of the supported types of counters. The type signature and
sample code:
\begin{lstlisting}
def bump[C]()(...) = ???

val counter = Counter(...)
val testCounter = TestCounter(...)

bump(counter)       // Should call counter.inc()
bump(testCounter)   // Should call testCounter.incr()
\end{lstlisting}


\subparagraph{Solution}

We will implement a typeclass \lstinline!Bumpable! whose type domain
contains the types \lstinline!Counter! and \lstinline!TestCounter!.
Typeclass instances should allow us to increment a counter of any
supported type. So, a typeclass instance value of type \lstinline!Bumpable[C]!
needs to contain a function of type \lstinline!C => Unit! that will
increment a counter of type \lstinline!C! appropriately:
\begin{lstlisting}
final case class Bumpable[C](bump: C => Unit)
\end{lstlisting}
We can now create the typeclass instances and implement the function
\lstinline!bump[C]!:
\begin{lstlisting}
object Bumpable {
  implicit val b1 = Bumpable[Counter](c => c.inc())
  implicit val b2 = Bumpable[TestCounter](c => c.incr())
  
  def bump[C](counter: C)(implicit ti: Bumpable[C]): Unit = ti.bump(counter)
}
\end{lstlisting}
An equivalent implementation with the type constraint syntax looks
like this:
\begin{lstlisting}
def bump[C: Bumpable](counter: C): Unit = implicitly[Bumpable[C]].bump(counter)
\end{lstlisting}


\subsubsection{Example \label{subsec:tc-Example-Pointed-type}\ref{subsec:tc-Example-Pointed-type}
(default values)}

Certain types have naturally chosen \textsf{``}default\textsf{''} values (e.g., integer
zero, empty string, empty array, etc.). The task is to implement a
function \lstinline!default[T]! restricted to types \lstinline!T!
for which default values are available. The required type signature
and sample tests:
\begin{lstlisting}
def default[T: HasDefault]: T = ???

scala> default[Int]
res0: Int = 0

scala> default[Double]
res1: Double = 0.0
\end{lstlisting}


\subparagraph{Solution}

We need to define a PTVF \lstinline!default[T]! with a type domain
that contains (at least) the types \lstinline!Int! and \lstinline!Double!.
For every supported type \lstinline!T!, we need to store the known
default value of that type. So, the typeclass instance can be defined
as a simple wrapper for values of type \lstinline!T!:
\begin{lstlisting}
final case class HasDefault[T](value: T)
\end{lstlisting}
Typeclass instances are declared straightforwardly:
\begin{lstlisting}
object HasDefault {
  implicit val defaultInt = HasDefault[Int](0)
  implicit val defaultDouble = HasDefault[Double](0.0)
  implicit val defaultString = HasDefault[String]("")
  implicit val defaultUnit = HasDefault[Unit](())
}
\end{lstlisting}
The implementation of \lstinline!default[T]! is written as
\begin{lstlisting}
def default[T](implicit ti: HasDefault[T]) = ti.value
\end{lstlisting}
When using the typeclass constraint syntax, the code is
\begin{lstlisting}
def default[T: HasDefault]: T = implicitly[HasDefault[T]].value
\end{lstlisting}

How to define an empty list as a default value for lists of \emph{any}
chosen type? We cannot write
\begin{lstlisting}
implicit val defaultList = HasDefault[List[A]](List())     // Error: `A` is undefined.
\end{lstlisting}
The type parameter \lstinline!A! needs to be defined in the left-hand
side. Since Scala 2 does not support \lstinline!val! declarations
with type parameters (Scala 3 will), we need to write the typeclass
instance as a \lstinline!def!:
\begin{lstlisting}
implicit def defaultList[A] = HasDefault[List[A]](List())
\end{lstlisting}

Another example of a \lstinline!HasDefault! instance with a type
parameter is for functions of type $A\rightarrow A$:
\begin{lstlisting}
implicit def defaultFunc[A]: HasDefault[A => A] = HasDefault[A => A](identity)
\end{lstlisting}

Types that have default values are also called \textbf{pointed}\index{pointed type}\index{types!pointed}
types. This book defines the typeclass \lstinline!Pointed! for pointed
\emph{functors} (Section~\ref{subsec:Pointed-functors:-motivation})
because they are more widely used than pointed types.

\subsubsection{Example \label{subsec:tc-Example-Semigroups}\ref{subsec:tc-Example-Semigroups}
(semigroups)}

In many cases, data items can be combined or merged into a larger
data item of the same type. For instance, two numbers can be added,
two sets combined into one set, two strings concatenated into one
string, and two lists into one list. The \textsf{``}merge\textsf{''} operation can
be defined as a function \lstinline!combine[T]! taking two arguments
of type \lstinline!T! and returning a new value of type \lstinline!T!.
We will denote that operation by $\oplus$, e.g., we write $x\oplus y$.
In all the examples just mentioned (integers, strings, lists, etc.),
that operation is associative:
\begin{equation}
\forall(x,y,z).\,\left(x\oplus y\right)\oplus z=x\oplus\left(y\oplus z\right)\quad.\label{eq:associativity-law-semigroup}
\end{equation}
This associativity law\index{associativity law!of semigroups} makes
parentheses in the expression $x\oplus y\oplus z$ unnecessary.

A type \lstinline!T! with an associative binary operation is called
a \textbf{semigroup}\index{semigroup}\index{typeclass!Semigroup@\texttt{Semigroup}}.
The task in this example is to define the semigroup operation for
the types \lstinline!Int!, \lstinline!String!, and \lstinline!List[A]!.

\subparagraph{Solution}

For every supported type $T$, the required data is a function of
type $T\times T\rightarrow T$. So, we define the typeclass as a wrapper
over that type:
\begin{lstlisting}
final case class Semigroup[T](combine: (T, T) => T)
\end{lstlisting}
The typeclass instances for the supported types are defined using
a short syntax as
\begin{lstlisting}
object Semigroup {
  implicit val semigroupInt = Semigroup[Int](_ + _)
  implicit val semigroupString = Semigroup[String](_ + _)
  implicit def semigroupList[A] = Semigroup[List[A]](_ ++ _)
}
\end{lstlisting}
The function \lstinline!combine[T]! is implemented as
\begin{lstlisting}
def combine[T](x: T, y: T)(implicit ti: Semigroup[T]): T = ti.combine(x, y)
\end{lstlisting}
Since \lstinline!combine! is a binary operation, it is convenient
to define infix method syntax for it:
\begin{lstlisting}
implicit class SemigroupSyntax[T: Semigroup](x: T) { def |+|(y: T): T = combine(x, y) }
\end{lstlisting}
After this definition, we may use the infix operation \lstinline!|+|!
like this,
\begin{lstlisting}
scala> List(1, 2, 3) |+| List(4)
res0: List[Int] = List(1, 2, 3, 4)
\end{lstlisting}
Due to the associativity law~(\ref{eq:associativity-law-semigroup}),
the result of \lstinline!x |+| y |+| z! does not depend on the choice
of parentheses: \lstinline!(x |+| y) |+| z == x |+| (y |+| z)!. This
makes programs written using the semigroup operation \lstinline!|+|!
easier to understand and reason about.

Semigroup types represent data that can be pairwise \textsf{``}merged\textsf{''} in
a certain well-defined way. Using the \lstinline!Semigroup! typeclass,
we can write code that is parameterized by the type of \textsf{``}mergeable\textsf{''}
data. As an example, given a \lstinline!Seq[T]! where the type \lstinline!T!
is a semigroup, we can \textsf{``}merge\textsf{''} all elements to compute a result
of type \lstinline!T!. This computation can be implemented as a function
parameterized by \lstinline!T!,
\begin{lstlisting}
def merge[T: Semigroup](ts: Seq[T]): T = ts.reduce(combine[T])
\end{lstlisting}
This function assumes a non-empty input sequence \lstinline!ts! whose
elements are of a semigroup type \lstinline!T!. We can also implement
the same function as an extension method,
\begin{lstlisting}
implicit class SumSyntax[T: Semigroup](ts: Seq[T]) { def merge: T = ts.reduce(combine[T]) }
\end{lstlisting}
With the previous definitions, we can now evaluate expressions such
as
\begin{lstlisting}
scala> Seq(1, 2, 3).merge
res1: Int = 6

scala> Seq(List(), List(true), List(), List(true, false)).merge
res2: List[Boolean] = List(true, true, false)
\end{lstlisting}

It is important that the associativity law~(\ref{eq:associativity-law-semigroup})
should hold for each of the supported types. If that is not so, programs
written with \lstinline!merge! will not work as expected. (For instance,
programmers would certainly expect that \lstinline!xs.merge |+| ys.merge == (xs ++ ys).merge!
for any sequences \lstinline!xs! and \lstinline!ys!.) However, the
code of the typeclass \emph{does not} check the associativity law.
It is the responsibility of the programmer to verify that the implementation
of each typeclass instance is lawful. 

The associativity law of integer addition is a standard arithmetic
identity
\[
\left(x+y\right)+z=x+\left(y+z\right)\quad.
\]
Verifying associativity for lists and strings (which are lists of
characters) is intuitively simple because concatenation preserves
the order of elements. If \lstinline!x!, \lstinline!y!, and \lstinline!z!
are lists, the concatenation \lstinline!(x ++ y) ++ z! is a list
containing all elements from \lstinline!x!, \lstinline!y!, and \lstinline!z!
in their original order. It is evident that the concatenation \lstinline!x ++ (y ++ z)!
is a list with the same elements in the same order. However, a rigorous
proof of the associativity law for lists, starting from the code of
the \lstinline!concat! function, requires significant work (see Section~\ref{subsec:Proofs-for-associativity-law-lists-and-arrays-concat}). 

\subsubsection{Example \label{subsec:tc-Example-semigroup-alternative-implementations}\ref{subsec:tc-Example-semigroup-alternative-implementations}
(alternative semigroup implementations)}

The definitions of the semigroup operation $\oplus$ as concatenation
for strings and as addition for integers may appear to be \textsf{``}natural\textsf{''}.
However, alternative implementations are useful in certain applications.
As long as the associativity law holds, \emph{any} function of type
$T\times T\rightarrow T$ may be used as the semigroup operation.
The task of this example is to show that the following implementations
of the semigroup operation are lawful and to implement the corresponding
typeclass instances in Scala.

\textbf{(a)} For any type $T$, define $x\oplus y\triangleq x$ (ignoring
the value of $y$).

\textbf{(b)} For pair types $T\triangleq A\times B$, define the operation
$\oplus$ by $\left(a_{1}\times b_{1}\right)\oplus\left(a_{2}\times b_{2}\right)\triangleq a_{1}\times b_{2}$.

\textbf{(c)} For $T\triangleq\text{String}$, define $x\oplus y$
as the longer of the strings $x$ and $y$.

\textbf{(d)} For $T\triangleq S\rightarrow S$ (the type $S$ is fixed),
define $x\oplus y\triangleq x\bef y$ (the forward function composition)
or $x\oplus y\triangleq x\circ y$ (the backward function composition).

\subparagraph{Solution}

\textbf{(a)} To verify the associativity law, use the definition $x\oplus y\triangleq x$
to compute 
\[
\left(x\oplus y\right)\oplus z=x\oplus z=x\quad,\quad x\oplus\left(y\oplus z\right)=x\quad.
\]
So the associativity law holds: $\left(x\oplus y\right)\oplus z=x\oplus\left(y\oplus z\right)$
for any $x$, $y$, $z$.

It is clear that $x\oplus y\oplus z\oplus...=x$ for any number of
values; the binary operation keeps the first value and ignores all
further values. We can implement this semigroup instance at once for
all types $T$:
\begin{lstlisting}
implicit def semigroup1[T] = Semigroup[T]{ (x, y) => x }
\end{lstlisting}
Similarly, the definition $x\oplus y\triangleq y$ gives an associative
binary operation for a (different) semigroup.

\textbf{(b)} To verify the associativity law:
\begin{align*}
\left(\left(a_{1}\times b_{1}\right)\oplus\left(a_{2}\times b_{2}\right)\right)\oplus\left(a_{3}\times b_{3}\right) & =\left(a_{1}\times b_{2}\right)\oplus\left(a_{3}\times b_{3}\right)=a_{1}\times b_{3}\quad,\\
\left(a_{1}\times b_{1}\right)\oplus\left(\left(a_{2}\times b_{2}\right)\oplus\left(a_{3}\times b_{3}\right)\right) & =\left(a_{1}\times b_{1}\right)\oplus\left(a_{2}\times b_{3}\right)=a_{1}\times b_{3}\quad.
\end{align*}
The implementation is possible for any types $A$, $B$:
\begin{lstlisting}
implicit def semigroup2[A, B] = Semigroup[(A, B)]{ case ((a1, b1), (a2, b2)) => (a1, b2) }
\end{lstlisting}

One use case for this semigroup is to maintain a pair of timestamps
for the first and the last events in a temporally ordered series.
Merging two such pairs for consecutive events means to keep the first
value from the first pair and the second value from the second pair.

\textbf{(c)} It is clear that $x\oplus y\oplus z$ is the longest
of the strings $x$, $y$, and $z$. Since the definition of \textsf{``}longest\textsf{''}
does not depend on the order in which we select pairs for comparison,
the operation is associative. (For the same reason, any \textsf{``}maximum\textsf{''}
or \textsf{``}minimum\textsf{''} operation is associative.) Implementation:
\begin{lstlisting}
implicit val semigroup3 = Semigroup[String]{ (x, y) => if (x.length > y.length) x else y }
\end{lstlisting}

\textbf{(d)} The composition of functions is associative (see proofs
in Section~\ref{subsec:Laws-of-function-composition}). Whether we
choose to define $x\oplus y\oplus z=x\bef y\bef z$ or $x\oplus y\oplus z=x\circ y\circ z=z\bef y\bef x$,
the results do not depend on inserting parentheses. The code for these
two typeclass instances is
\begin{lstlisting}
implicit def semigroup4[S] = Semigroup[S => S]{ (x, y) => x andThen y }
implicit def semigroup5[S] = Semigroup[S => S]{ (x, y) => x compose y }
\end{lstlisting}


\subsubsection{Example \label{subsec:tc-Example-Monoids}\ref{subsec:tc-Example-Monoids}
(monoids)}

When a data type is a semigroup, it is often possible to find a special
value that acts as an \textsf{``}default\textsf{''} value with respect to the semigroup
operation. Merging with the default value will not change any other
value. For instance, concatenating with an empty list does not change
any other list; so the empty list plays the role of the default value
for lists. Merging an empty set with any other set does not change
the other set; so the empty set is the default for sets.

A semigroup with such a default value is called a \textbf{monoid}\index{monoid}.
Formally, a type $T$ is a monoid when it has an associative binary
operation $\oplus_{T}$ and a chosen default or \textsf{``}empty\textsf{''} value
$e^{:T}$ such that 
\begin{equation}
\text{for all }x^{:T}:\quad e\oplus_{T}x=x\quad,\quad\quad x\oplus_{T}e=x\quad.\label{eq:identity-laws-of-monoid}
\end{equation}
The laws~(\ref{eq:identity-laws-of-monoid}) are called the \textbf{identity
laws}\index{identity laws!of monoid} of monoid. 

The task in this example is to define a typeclass describing monoids. 

\subparagraph{Solution}

The typeclass\index{typeclass!Monoid@\texttt{Monoid}} instances should
contain the same information as semigroups and additionally the default
value of type $T$. So, we write
\begin{lstlisting}
final case class Monoid[T](combine: (T, T) => T, empty: T)
\end{lstlisting}
Let us define some typeclass instances for illustration:
\begin{lstlisting}
object Monoid {
  implicit val monoidInt = Monoid[Int](_ + _, 0)
  implicit val monoidString = Monoid[String](_ + _, "")
  implicit def monoidList[A] = Monoid[List[A]](_ ++ _, List())
  implicit def monoidFunc[A] = Monoid[A => A](_ andThen _, identity)
}
\end{lstlisting}

Monoids formalize the general properties of data aggregation. Section~\ref{subsec:Monoids-constructions}
will study monoids in more detail and show further examples of their
use. At this point, we look at one more example that defines a \lstinline!Monoid!
instance using two previously defined typeclasses, \lstinline!Semigroup!
and \lstinline!HasDefault!.

\subsubsection{Example \label{subsec:tc-Example-Monoids-1}\ref{subsec:tc-Example-Monoids-1}
(monoids as semigroups with default)}

A monoid combines the properties of a semigroup and a type with a
default value. If a type \lstinline!T! is a semigroup and has a default
value, it is likely that \lstinline!T! is a monoid. The task is to
define a \lstinline!Monoid! typeclass instance given \lstinline!Semigroup!
and \lstinline!HasDefault! instances for a type \lstinline!T!.

\subparagraph{Solution}

We need to define a function \lstinline!monoidOf[T]! that returns
the required monoid typeclass instance for \lstinline!T!. The typeclass
constraints for this function are \lstinline!Semigroup! and \lstinline!HasDefault!.
So the type signature must be
\begin{lstlisting}
def monoidOf[T](implicit ti1: Semigroup[T], ti2: HasDefault[T]): Monoid[T] = ???
\end{lstlisting}
To implement a value of type \lstinline!Monoid[T]!, we need to provide
a function of type $T\times T\rightarrow T$ and a value of type $T$.
Precisely that data is available in the typeclass instances of \lstinline!Semigroup!
and \lstinline!HasDefault!, and so it is natural to use them,
\begin{lstlisting}
def monoidOf[T](implicit ti1: Semigroup[T], ti2: HasDefault[T]): Monoid[T] =
  Monoid(ti1.combine, ti2.value)
\end{lstlisting}
Using the type constraint syntax, the equivalent code is
\begin{lstlisting}
def monoidOf[T: Semigroup : HasDefault]: Monoid[T] =
  Monoid(implicitly[Semigroup[T]].combine, implicitly[HasDefault[T]].value)
\end{lstlisting}
We can also define this function as an \lstinline!implicit!, so that
every type \lstinline!T! with a \lstinline!Semigroup! and \lstinline!HasDefault!
instances will automatically receive a \lstinline!Monoid! typeclass
instance as well.

Writing the types of the \lstinline!Semigroup!, \lstinline!HasDefault!,
and \lstinline!Monoid! instances in the type notation, we get
\[
\text{Semigroup}^{T}\triangleq T\times T\rightarrow T\quad,\quad\quad\text{HasDefault}^{T}\triangleq T\quad,\quad\quad\text{Monoid}^{T}\triangleq\left(T\times T\rightarrow T\right)\times T\quad.
\]
It is clear that
\[
\text{Monoid}^{T}\cong\text{Semigroup}^{T}\times\text{HasDefault}^{T}\quad.
\]
Indeed, the code for \lstinline!monoidOf! computes a pair of values
from the \lstinline!Semigroup! and \lstinline!HasDefault! instances. 

Is this implementation lawful with respect to the monoid laws? The
associativity law will hold for the monoid if the \lstinline!Semigroup!
typeclass instance was already lawful. However, the value stored in
the \lstinline!HasDefault! instance is not guaranteed to satisfy
the identity laws~(\ref{eq:identity-laws-of-monoid}) with respect
to the \lstinline!combine! operation stored in the \lstinline!Semigroup!
instance. The programmer must verify that the identity laws hold.
It can happen that, for some type $T$, typeclass instances of \lstinline!Semigroup!
and \lstinline!HasDefault! already exist but are not \textsf{``}compatible\textsf{''},
so that the monoid identity laws do not hold. In that case, a simple
combination of \lstinline!Semigroup! and \lstinline!HasDefault!
instances will not work, and a different \lstinline!Monoid! instance
must be defined.

Are there alternative implementations of the \lstinline!Monoid! typeclass
instance given \lstinline!Semigroup! and \lstinline!HasDefault!
instances? The function \lstinline!monoidOf! needs to produce a value
of type $\left(T\times T\rightarrow T\right)\times T$ given values
of type $T\times T\rightarrow T$ and a value of type $T$:
\[
\text{monoidOf}:\left(T\times T\rightarrow T\right)\times T\rightarrow\left(T\times T\rightarrow T\right)\times T\quad.
\]
When the type signature of \lstinline!monoidOf! is written in this
notation, it is clear that \lstinline!monoidOf! should be the identity
function; indeed, that is what our code translates to. Although there
are many other implementations of the same type signature, only the
code shown above will satisfy the monoid laws. An example of an unlawful
implementation is
\begin{lstlisting}
def badMonoidOf[T](implicit ti1: Semigroup[T], ti2: HasDefault[T]): Monoid[T] =
  Monoid((x, y) => ti1.combine(x, ti1.combine(x, y)), ti2.value)
\end{lstlisting}
This implementation defines the monoid operation as $x\oplus x\oplus y$
instead of the correct definition $x\oplus y$. If we set $y=e_{T}$,
we will get $x\oplus x$ instead of $x$, violating one of the identity
laws.

\subsection{Typeclasses for type constructors\label{subsec:Typeclasses-for-type-constructors}}

An example of a function parameterized by a type constructor is

\begin{wrapfigure}{l}{0.65\columnwidth}%
\vspace{-0.85\baselineskip}
\begin{lstlisting}
def inject[F[_]: Functor, A, B](a: A, f: F[B]): F[(A, B)] = ???
\end{lstlisting}
\vspace{-0.85\baselineskip}
\end{wrapfigure}%

\noindent The intention is to require the type parameter \lstinline!F!
to be a functor. We can use a suitable typeclass to implement this
constraint. Since the type parameter \lstinline!F! is itself a type
constructor, the typeclass constructor will use the syntax \lstinline!Functor[F[_]]!. 

What information needs to be wrapped by a typeclass instance? A functor
\lstinline!F! must have a \lstinline!map! function with the standard
type signature

\begin{wrapfigure}{l}{0.43\columnwidth}%
\vspace{-0.75\baselineskip}
\begin{lstlisting}
def map[A, B](fa: F[A])(f: A => B): F[B]
\end{lstlisting}
\vspace{-0.05\baselineskip}
\end{wrapfigure}%

\noindent In the type notation, this type signature is written as\vspace{-0.45\baselineskip}
\[
\text{map}:\forall(A,B).\,F^{A}\rightarrow\left(A\rightarrow B\right)\rightarrow F^{B}\quad.
\]
\vspace{-1.5\baselineskip}

\noindent So, a typeclass instance of the \lstinline!Functor! typeclass
must contain this function as a value. But defining the typeclass
as before via a \lstinline!case class! does not work with Scala 2,
\begin{lstlisting}[mathescape=true]
final case class Functor[F[_]](map: $\forall(A,B).\,$F[A] => (A => B) => F[B])   // Not possible in Scala 2.
\end{lstlisting}
Scala 3 will directly support an argument type that \emph{itself}
contains type quantifiers such as $\forall(A,B)$. In Scala 2, we
need to represent such \textsf{``}nested\textsf{''} type quantifiers by writing a
\lstinline!trait! with a \lstinline!def! method:\index{typeclass!Functor@\texttt{Functor}}

\begin{wrapfigure}{l}{0.43\columnwidth}%
\vspace{-0.75\baselineskip}
\begin{lstlisting}
trait Functor[F[_]] {
  def map[A, B](fa: F[A])(f: A => B): F[B]
}
\end{lstlisting}
\vspace{-0.75\baselineskip}
\end{wrapfigure}%

\noindent The type constructor \lstinline!Functor! has the type parameter
\lstinline!F[_]!, which must be itself a type constructor. For any
type constructor \lstinline!F!, a value of type \lstinline!Functor[F]!
is a wrapper for a value of type $\forall(A,B).\,F^{A}\rightarrow\left(A\rightarrow B\right)\rightarrow F^{B}$.
Values of type \lstinline!Functor! (i.e., typeclass instances) are
implemented with the \textsf{``}\lstinline!new { ... }!\textsf{''} syntax:
\begin{lstlisting}
implicit val functorSeq = new Functor[Seq] {
  def map[A, B](fa: Seq[A])(f: A => B): Seq[B] = fa.map(f)
}
\end{lstlisting}
This is currently the most common way of defining typeclasses in Scala.

It is convenient to declare \lstinline!map! as an extension method
on the \lstinline!Functor! type constructors,
\begin{lstlisting}
implicit class FunctorSyntax[F[_]: Functor, A](fa: F[A]) {    // Syntax helper class.
  def map[B](f: A => B): F[B] = implicitly[Functor[F]].map(fa)(f)
}
\end{lstlisting}
If this class definition is in scope, the \lstinline!map! method
becomes available for values of functor types.

Using the \lstinline!Functor! typeclass and the syntax helper, we
can now implement the function \lstinline!inject!:
\begin{lstlisting}
def inject[F[_]: Functor, A, B](a: A, f: F[B]): F[(A, B)] = f.map { b => (a, b) }

scala> inject("abc", Seq(1, 2, 3))   // Assuming that implicit Functor[Seq] is in scope.
res0: Seq[(String, Int)] = List(("abc", 1), ("abc", 2), ("abc", 3))
\end{lstlisting}
 Just like the \lstinline!Monoid! typeclass, the code of the \lstinline!Functor!
typeclass does not enforce the functor laws on the implementation.
It is the programmer responsibility to verify that the laws hold.

One way of checking the laws is to use the \texttt{scalacheck} library\index{verifying laws with scalacheck@verifying laws with \texttt{scalacheck}}\footnote{\texttt{\href{https://www.scalacheck.org}{https://www.scalacheck.org}}}
that automatically runs random tests for the given assertions, trying
to discover a set of values for which some assertion fails. Using
the \lstinline!Functor! typeclass constraint, we can implement a
function (in our terminology, a PTVF) that checks the functor laws
for \emph{any} given type constructor \lstinline!F[_]!:
\begin{lstlisting}
import org.scalacheck.Arbitrary                                 // Necessary imports and definitions.
import org.scalatest.prop.GeneratorDrivenPropertyChecks
class FunctorTest extends Matchers with GeneratorDrivenPropertyChecks {
  def checkFunctorLaws[F[_], A, B, C]()(implicit ff: Functor[F],     // Use the `Arbitrary` typeclass
      fa: Arbitrary[F[A]], ab: Arbitrary[A => B], bc: Arbitrary[B => C]) = {    // from `scalacheck`.
    forAll { (fa: F[A]) => fa.map(identity[A]) shouldEqual fa }  // Identity law. "For all `fa`, ..."
    forAll { (f: A => B, g: B => C, fa: F[A]) =>          // Composition law. The assertion must hold
      fa.map(f).map(g) shouldEqual fa.map(f andThen g)    // for all `f`, `g`, `fa`.
    }
  }
  // Check the laws for F = Seq using specific types instead of type parameters A, B, C.
  checkFunctorLaws[Seq, Int, String, Double]()
}
\end{lstlisting}

The \texttt{scalacheck} library will substitute a large number of
random values into the given assertions, Note that the laws are being
tested only with a finite number of values and with type parameters
set to specific types. While it is useful to test laws with \texttt{scalacheck}
(we might find a bug), only a symbolic derivation provides a rigorous
proof that the laws hold. One of the main themes of this book is to
show how to perform symbolic derivations efficiently.

\section{Deriving typeclass instances via structural analysis of types}

In Chapter~\ref{chap:Functors,-contrafunctors,-and} we analyzed
the structure of functors by checking which of the six standard type
constructions can make new functors out of previous ones. We will
now apply the same\index{structural analysis} \index{types!structural analysis}\textbf{structural
analysis} to various typeclasses. Is a product of two monoids a monoid?
Is a co-product of two semigroups a semigroup? Answers to such questions
will enable us to:
\begin{itemize}
\item Quickly decide whether a given type can have a typeclass instance
of \lstinline!Monoid!, \lstinline!Semigroup!, etc.
\item If so, derive the code for the new typeclass instance without guessing.
\item Have assurance that the required typeclass laws will hold for newly
constructed instances.
\end{itemize}
In the following sections, we will show how to use this approach for
some simple typeclasses.

\subsection{Extractors}

Our first typeclass is a generalization of Example~\ref{subsec:tc-Example-metadata-extractors}.
The functionality was to extract metadata of fixed types from a value
of type \lstinline!T!. The typeclass instance contained a pair of
functions,
\begin{lstlisting}
final case class HasMetadata[T](getName: T => String, getCount: T => Long)
\end{lstlisting}
In the type notation, this type constructor is written as
\[
\text{HasMetadata}^{T}\triangleq(T\rightarrow\text{String})\times(T\rightarrow\text{Long})\quad.
\]
A standard type equivalence (see Table~\ref{tab:Logical-identities-with-function-types})
shows that this type is equivalent to $T\rightarrow\text{String}\times\text{Long}$.
This motivates us to denote $\text{String}\times\text{Long}$ by $Z$
and to consider a typeclass whose instances are values of type $T\rightarrow Z$.
We may call this typeclass a \textsf{``}$Z$-extractor\index{extractor typeclass}\index{typeclass!Extractor@\texttt{Extractor}}\textsf{''}
since types $T$ from its type domain permit us somehow to extract
values of type $Z$. With a fixed type $Z$, we denote the typeclass
by
\[
\text{Extractor}^{T}\triangleq T\rightarrow Z\quad.
\]
\begin{lstlisting}
final case class Extractor[Z, T](extract: T => Z)
\end{lstlisting}
What kind of types can have an Extractor typeclass instance? To answer
that question, we apply structural analysis and check whether any
of the standard type constructions produce new typeclass instances.
The results are summarized in Table~\ref{tab:Type-constructions-for-Extractor}.
Let us show the required calculations.

\paragraph{Fixed types}

We check whether an \lstinline!Extractor! typeclass instance can
be computed for the \lstinline!Unit! type or for another fixed type
$C$. To compute $\text{Extractor}^{\bbnum 1}=\bbnum 1\rightarrow Z$
requires creating a value of type $Z$ from scratch, which we cannot
do in a fully parametric function. For a fixed type $C$, a value
of type $\text{Extractor}^{C}=C\rightarrow Z$ can be computed only
if we can compute a value of type $Z$ given a value of type $C$.
This is possible only if we choose $C$ as $C=Z$. The typeclass instance
for $\text{Extractor}^{Z}$ is implemented as an identity function
of type $Z\rightarrow Z$:
\begin{lstlisting}
implicit def extractorZ[Z] = Extractor[Z, Z](identity)
\end{lstlisting}


\paragraph{Type parameters}

Creating a typeclass instance $\text{Extractor}^{A}$ for an arbitrary
type $A$ means to compute $\forall A.\,A\rightarrow Z$; this is
not possible since we cannot create values of type $Z$ using only
a value of an unknown type $A$. So, there is no \lstinline!Extractor!
for arbitrary types \lstinline!A!.

\paragraph{Products}

If the types $A$ and $B$ are known to be within the type domain
of \lstinline!Extractor!, can we add the pair $A\times B$ to that
domain? If we can extract a value of type $Z$ from each of two values
$a^{:A}$ and $b^{:B}$, we can certainly extract a value of type
$Z$ from the product $a\times b$ by choosing to extract only from
$a$ or only from $b$. So, it appears that we have two possibilities
for implementing the typeclass for $A\times B$. Reasoning more rigorously,
we see that computing a new typeclass instance from two previous ones
requires implementing a conversion function with type signature
\[
\forall(A,B,Z).\,\text{Extractor}^{A}\times\text{Extractor}^{B}\rightarrow\text{Extractor}^{A\times B}=\left(A\rightarrow Z\right)\times\left(B\rightarrow Z\right)\rightarrow A\times B\rightarrow Z\quad.
\]
We can derive only two fully parametric implementations of this type
signature: 
\[
f^{:A\rightarrow Z}\times g^{:B\rightarrow Z}\rightarrow a\times b\rightarrow f(a)\quad\quad\text{ and }\quad\quad f^{:A\rightarrow Z}\times g^{:B\rightarrow Z}\rightarrow a\times b\rightarrow g(b)\quad.
\]
Both implementations give a valid \lstinline!Extractor! instance
(since there are no laws to check). However, every choice will use
one of the two \lstinline!Extractor! instances and ignore the other.
So, we can simplify this construction by keeping the typeclass constraint
only for $A$ and allowing \emph{any} type $B$,
\[
\text{extractorPair}:\forall(A,B,Z).\,\text{Extractor}^{A}\rightarrow\text{Extractor}^{A\times B}\quad.
\]
\begin{lstlisting}
def extractorPair[Z, A, B](implicit ti: Extractor[Z, A]) =
  Extractor[Z, (A, B)] { case (a, b) => ti.extract(a) }
\end{lstlisting}
If $A$ has an \lstinline!Extractor! instance, the product of $A$
with any type $B$ also has an \lstinline!Extractor! instance. Examples
of this construction are $Z\times B$ and $P\times Q\times Z$ (since
the type $Z$ itself has an \lstinline!Extractor! instance).

\paragraph{Co-products}

Given typeclass instances $\text{Extractor}^{A}$ and $\text{Extractor}^{B}$,
can we compute a value of type $\text{Extractor}^{A+B}$? Writing
out the types, we get
\[
\text{Extractor}^{A}\times\text{Extractor}^{B}\rightarrow\text{Extractor}^{A+B}=\left(A\rightarrow Z\right)\times\left(B\rightarrow Z\right)\rightarrow A+B\rightarrow Z\quad.
\]
Due to a known type equivalence (Table~\ref{tab:Logical-identities-with-function-types}),
we have a unique implementation of this function:
\[
\text{extractorEither}\triangleq f^{:A\rightarrow Z}\times g^{:B\rightarrow Z}\rightarrow\,\begin{array}{|c||c|}
 & Z\\
\hline A & a\rightarrow f(a)\\
B & b\rightarrow g(b)
\end{array}\quad.
\]
\begin{lstlisting}
def extractorEither[Z, A, B](implicit ti1: Extractor[Z, A], ti2: Extractor[Z, B]) =
  Extractor[Z, Either[A, B]] {
    case Left(a)    => ti1.extract(a)
    case Right(b)   => ti2.extract(b)
}
\end{lstlisting}
So, the co-product of $A$ and $B$ can be given a unique \lstinline!Extractor!
instance.

Since the product and the co-product constructions preserve \lstinline!Extractor!
instances, we conclude that any polynomial type expression has an
\lstinline!Extractor! instance as long as every product type contains
at least one $Z$ or another \lstinline!Extractor! type. For example,
the type expression 
\[
A\times Z+Z\times(P+Z\times Q)+B\times C\times Z
\]
is of that form and therefore has an \lstinline!Extractor! instance.
Generally, a polynomial in $Z$ will have an \lstinline!Extractor!
instance only if the polynomial is of the form $Z\times P^{Z}$ for
some functor $P$.

\paragraph{Function types}

We need to investigate whether $C\rightarrow A$ or $A\rightarrow C$
can have an \lstinline!Extractor! instance for some choice of $C$,
assuming that we have an instance for $A$. The required conversion
functions must have type signatures
\[
\text{Extractor}^{A}\rightarrow\text{Extractor}^{A\rightarrow C}\quad\quad\text{ or }\quad\quad\text{Extractor}^{A}\rightarrow\text{Extractor}^{C\rightarrow A}\quad.
\]
Writing out the types, we find
\[
\left(A\rightarrow Z\right)\rightarrow\left(A\rightarrow C\right)\rightarrow Z\quad\quad\text{ or }\quad\quad\left(A\rightarrow Z\right)\rightarrow\left(C\rightarrow A\right)\rightarrow Z\quad.
\]
None of these type signatures can be implemented. The first one is
hopeless since we do not have values of type $A$; the second one
is missing values of type $C$. However, since the type $C$ is fixed,
we may store a value of type $C$ as part of the newly constructed
type. So, we consider the pair type $C\times\left(C\rightarrow A\right)$
and find that its \lstinline!Extractor! instance, i.e., a value of
type $C\times\left(C\rightarrow A\right)\rightarrow Z$, can be derived
from a value of type $A\rightarrow Z$ as
\[
f^{:A\rightarrow Z}\rightarrow c^{:C}\times g^{:C\rightarrow A}\rightarrow f(g(c))\quad.
\]
\begin{lstlisting}
def extractorFunc[Z, A, C](implicit ti: Extractor[Z, A]) =
  Extractor[Z, (C, C => A)] { case (c, g) => ti.extract(g(c)) }
\end{lstlisting}
Examples of this construction are the type expressions $C\times\left(C\rightarrow Z\right)$
and $D\times\left(D\rightarrow Z\times P\right)$.

Another situation where an \lstinline!Extractor! instance exists
for the type $C\rightarrow A$ is when the type $C$ has a known \textsf{``}default
value\textsf{''} $e_{C}$ (as in the \lstinline!HasDefault! typeclass). In
that case, we may omit the first $C$ in $C\times(C\rightarrow A)$
and instead substitute the default value when necessary.

\paragraph{Recursive types}

We can add recursion to any of the constructions that create a new
type with an \lstinline!Extractor! instance out of a previous such
type. For clarity, let us use type constructors $F_{1}$, $F_{2}$,
etc., for describing the new types produced out of previous extractor
types. For the product construction, we define $F_{1}^{B,A}\triangleq A\times B$.
For the co-product construction, define $F_{2}^{B,A}\triangleq B+A$
(where $B$ must be also an extractor type). For the function construction,
define $F_{3}^{C,A}\triangleq C\times\left(C\rightarrow A\right)$.

Any recursive type equation that uses $F_{1}$, $F_{2}$, and/or $F_{3}$
will define a new recursive type with an \lstinline!Extractor! instance.
An example is the type equation involving the composition of $F_{2}$
and $F_{1}$:
\begin{equation}
T\triangleq F_{2}^{Z\times P,F_{1}^{T,Q}}=Z\times P+Q\times T\quad.\label{eq:example-recursive-equation-extractor}
\end{equation}
We can visualize this recursive type as an \textsf{``}infinite disjunction\textsf{''}:
\begin{align*}
 & T\cong Z\times P+Q\times T\\
 & \cong Z\times P+Q\times\left(Z\times P+Q\times\left(Z\times P+...\right)\right)\\
 & \cong Z\times P\times(\bbnum 1+Q+Q\times Q+...)\cong Z\times P\times\text{List}^{Q}\quad.
\end{align*}
Since the resulting type is equivalent to $Z\times C$ where $C\triangleq P\times\text{List}^{Q}$,
we find that the recursive equation~(\ref{eq:example-recursive-equation-extractor})
is equivalent to the product construction with a different type.

This will happen with any recursive equation containing $F_{1}$ and
$F_{2}$ (but no $F_{3}$): since $F_{1}$ and $F_{2}$ are polynomial
functors, the resulting type $T$ will be a recursive polynomial in
$Z$. To support an \lstinline!Extractor! instance, such polynomials
must be the form $Z\times P^{Z}$ for some functor $P$.

Recursive equations involving $F_{3}$ will produce new examples of
\lstinline!Extractor! types, such as
\begin{equation}
T\triangleq F_{3}^{C,F_{2}^{Z,F_{1}^{T,P}}}=C\times\left(C\rightarrow Z+P\times T\right)\quad.\label{eq:example-good-recursive-equation-extractor}
\end{equation}
Heuristically, this type can be seen as an \textsf{``}infinite\textsf{''} exponential-polynomial
type expression
\[
T=C\times\left(C\rightarrow Z+P\times C\times\left(C\rightarrow Z+P\times C\times\left(C\rightarrow Z+...\right)\right)\right)\quad.
\]
Types of this form are useful in some applications involving lazy
streams.

We will now show how to define an \lstinline!Extractor! instance
for any recursive type defined using $F_{1}$, $F_{2}$, and/or $F_{3}$.
A recursive type equation defining a type $T$ can be written generally
as $T\triangleq S^{T}$, where $S$ is a type constructor built up
by composing $F_{1}$, $F_{2}$, and/or $F_{3}$ in some way. (The
type constructor $S$ may use $Z$ or other fixed types.) For each
of $F_{1}$, $F_{2}$, and/or $F_{3}$, we implemented a function
with type 
\[
\text{extractorF}:\text{Extractor}^{A}\rightarrow\text{Extractor}^{F^{A}}\quad.
\]
Since $S$ is a composition of $F_{1}$, $F_{2}$, and/or $F_{3}$,
we are able to implement a function 
\[
\text{extractorS}:\text{Extractor}^{A}\rightarrow\text{Extractor}^{S^{A}}\quad.
\]
The \lstinline!Extractor! instance for the recursive type $T$ is
then defined recursively as
\[
x^{:T\rightarrow Z}\triangleq\text{extractorS}\left(x\right)\quad.
\]
The types match because the type $T$ is equivalent to the type $S^{T}$.
As long as the definition of the recursive type $T$ is valid (i.e.,
the type recursion terminates), the extractor function will also terminate.

To illustrate this construction, let us derive an \lstinline!Extractor!
instance for the type $T$ defined by Eq.~(\ref{eq:example-good-recursive-equation-extractor}).
That equation has the form $T=S^{T}$ with the type constructor $S$
defined by $S^{A}\triangleq C\times\left(C\rightarrow Z+P\times A\right)$.
\begin{lstlisting}
type S[A] = (C, C => Either[Z, (P, A)])  // The fixed types `C` and `P` must be defined previously.
final case class TypeT(t: S[TypeT])      // Define the recursive type `TypeT`. 
\end{lstlisting}
To implement the function of type \lstinline!Extractor[T] => Extractor[S[T]]!,
which is $\left(T\rightarrow Z\right)\rightarrow S^{T}\rightarrow Z$,
we begin with a typed hole
\[
f^{:T\rightarrow Z}\rightarrow s^{:C\times\left(C\rightarrow Z+P\times T\right)}\rightarrow\text{???}^{:Z}\quad.
\]
To fill $\text{???}^{:Z}$, we could apply $f^{:T\rightarrow Z}$
to some value of type $T$; but the only value of type $T$ can be
obtained if we apply the function of type $C\rightarrow Z+P\times T$
to the given value of type $C$. So we write
\[
f^{:T\rightarrow Z}\rightarrow c^{:C}\times g^{:C\rightarrow Z+P\times T}\rightarrow g(c)\triangleright\text{???}^{:Z+P\times T\rightarrow Z}\quad.
\]
The new typed hole has a function type. We can write the code in matrix
notation as
\[
\text{extractorS}\triangleq f^{:T\rightarrow Z}\rightarrow c^{:C}\times g^{:C\rightarrow Z+P\times T}\rightarrow g(c)\triangleright\,\begin{array}{|c||c|}
 & Z\\
\hline Z & \text{id}\\
P\times T & \_^{:P}\times t^{:T}\rightarrow f(t)
\end{array}\quad.
\]
\begin{lstlisting}
def extractorS[A](f: Extractor[A]): Extractor[S[A]] = Extractor[S[A]] { case (c, g) =>
  g(c) match {
    case Left(z)         => z
    case Right((_, t))   => f.extract(t)
  }
}
\end{lstlisting}

The recursive construction defines an \lstinline!Extractor! instance
for $T$ by a recursive equation,
\begin{equation}
\text{extractorT}\triangleq\text{extractorS}\left(\text{extractorT}\right)\quad.\label{eq:recursive-extractor-def}
\end{equation}
\begin{lstlisting}
def extractorT: Extractor[TypeT] = Extractor[TypeT] { case TypeT(t) =>
  extractorS(extractorT).extract(t)
}
\end{lstlisting}
To test this code, we define a value of type $T$ while setting \lstinline!C = Int!,
\lstinline!P = Boolean!, and \lstinline!Z = String!:
\begin{lstlisting}
val t = TypeT((10, x => Right((true, TypeT((x * 2, y => Left("abc")))))))

scala> extractorT.extract(t) // The recursive definition of `extractorT` terminates.
res0: String = abc
\end{lstlisting}


\paragraph{Why the recursion terminates}

The above code shows that the recursive definition~(\ref{eq:recursive-extractor-def})
terminates. Why does it? A recursive definition of the form $x\triangleq f(x)$
could create an infinite loop, as in this code:
\begin{lstlisting}
def f(x: Int): Int = x + 1
def x: Int = f(x)

scala> x                     // Infinite loop: f(f(f(f(...)))
java.lang.StackOverflowError
\end{lstlisting}
The code for \lstinline!extractorT! works because \lstinline!extractorT!
is a value of a \emph{function} type, and because the presence of
the case class \lstinline!Extractor! forces us to rewrite Eq.~(\ref{eq:recursive-extractor-def})
in the form of an \textsf{``}expanded function\textsf{''}, 
\[
\text{extractorT}\triangleq t\rightarrow\text{extractorS}\left(\text{extractorT}\right)(t)\quad.
\]
\begin{lstlisting}
def extractorT: Extractor[TypeT] = Extractor { case TypeT(t) => extractorS(extractorT).extract(t) }
\end{lstlisting}
Although a function $f$ is equivalent to its \textbf{expanded form}
\index{expanded form of a function!use in recursive values} $t\rightarrow f(t)$,
there is an important difference: using expanded forms in the code
will make recursive definitions \index{recursive function!termination}
terminate.

To see an example of that, consider a recursive equation $f\triangleq k(f)$,
where $k$ is some function. The Scala code \lstinline!val f = k(f)!
creates an infinite loop when we compute anything that involves $f$:
\begin{lstlisting}[mathescape=true]
def k(f: Int => Int): Int => Int = { x => if (x <= 0) 1 else 2 * f(x - 1) }
def f: Int => Int = k(f)    // This definition is invalid!

scala> f                   // Infinite loop: k(k(k(k(...)))
java.lang.StackOverflowError

scala> f(4)                // Infinite loop: k(k(k(k(...)))(4)
java.lang.StackOverflowError
\end{lstlisting}
This code is clearly invalid. But if we expand the right-hand side
of the recursive equation to 
\[
f\triangleq t\rightarrow k(f)(t)
\]
instead of $f\triangleq k(f)$, the code will become valid, and the
infinite loop disappears:
\begin{lstlisting}[mathescape=true]
def f: Int => Int = { x => k(f)(x) }   // This defines $\color{dkgreen} f(n) = 2^n $ for $\color{dkgreen}n \geq 0$.

scala> f                               // We can compute f without an infinite loop.
res0: Int => Int = <function1>

scala> f(4)                            // We can compute f(4) without an infinite loop.
res1: Int = 16
\end{lstlisting}
The recursive use of $f$ now occurs \emph{within} a function body,
and so $k(f)$ is evaluated only when $f$ is applied to an argument.
This allows the recursive definition of $f$ to terminate.

\paragraph{Summary}

We derived the constructions that create new types with \lstinline!Extractor!
typeclass instances from previous ones. Any number of these constructions
can be combined to create a new type expression that will always have
an \lstinline!Extractor! instance. An example is the type expression
\[
K^{Z,P,Q,R,S}\triangleq Z\times P+Q\times\left(Q\rightarrow Z+R\times\left(R\rightarrow Z\times S\right)\right)\quad.
\]
Since the type $K$ is built up step by step from fixed types via
the product, co-product, and function constructions, an \lstinline!Extractor!
instance for $K$ can be derived systematically with no guessing:
\begin{lstlisting}[mathescape=true]
type K[Z,P,Q,R,S] = Either[(Z, P), (Q, Q => Either[Z, (R, R => (Z, S))])]
implicit def extractorK[Z,P,Q,R,S]: Extractor[Z, K[Z,P,Q,R,S]] = {   // Extractor values for types:
  implicit val e1 = extractorPair[Z, Z, S]                           // $\color{dkgreen} Z \times S $. Needs Extractor[Z, Z].
  implicit val e2 = extractorFunc[Z, (Z, S), R]                      // $\color{dkgreen} R\times\left(R\Rightarrow Z\times S\right) $.
  implicit val e3 = extractorEither[Z, Z, (R, R => (Z, S))]          // $\color{dkgreen} Z+R\times\left(R\Rightarrow Z\times S\right) $.
  implicit val e4 = extractorFunc[Z, Either[Z, (R, R => (Z, S))], Q] // $\color{dkgreen} Q\times\left(Q\Rightarrow Z+R\times\left(R\Rightarrow Z\times S\right)\right) $.
  implicit val e5 = extractorPair[Z, Z, P]                           // $\color{dkgreen} Z\times P $.
  extractorEither[Z, (Z,P), (Q, Q => Either[Z, (R, R => (Z, S))])]   // Extractor for type $\color{dkgreen} K $.
}
\end{lstlisting}
The code computes each implicit value \lstinline!e1!, \lstinline!e2!,
..., using constructions that require previously computed values to
be present as implicits.

The \lstinline!Extractor! typeclass is often used with \lstinline!Z = String!
as a way to \textsf{``}print\textsf{''} values of different types, and it is then
called \lstinline!Show!\index{typeclass!Show@\texttt{Show}}. When
\lstinline!Z = Array[Byte]!, the typeclass is often called a \textsf{``}serializer\index{serializer}\textsf{''}. 

\begin{table}
\begin{centering}
\begin{tabular}{|c|c|c|}
\hline 
\textbf{\footnotesize{}Construction} & \textbf{\footnotesize{}Type signature to implement} & \textbf{\footnotesize{}Results}\tabularnewline
\hline 
\hline 
{\footnotesize{}The }\lstinline!Unit!{\footnotesize{} type, or other
fixed type $C$} & {\footnotesize{}$\text{Extractor}^{\bbnum 1}$ or $\text{Extractor}^{C}$} & {\footnotesize{}$\text{Extractor}^{Z}$}\tabularnewline
\hline 
{\footnotesize{}Product of extractor type $A$ and any $B$} & {\footnotesize{}$\text{Extractor}^{A}\rightarrow\text{Extractor}^{A\times B}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Co-product of extractor types $A$ and $B$} & {\footnotesize{}$\text{Extractor}^{A}\times\text{Extractor}^{B}\rightarrow\text{Extractor}^{A+B}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Function from or to another type $C$} & {\footnotesize{}$\text{Extractor}^{A}\rightarrow\text{Extractor}^{A\rightarrow C}$
or $\text{Extractor}^{C\rightarrow A}$} & {\footnotesize{}$\text{Extractor}^{C\times\left(C\rightarrow A\right)}$}\tabularnewline
\hline 
{\footnotesize{}Recursive type} & {\footnotesize{}$\text{Extractor}^{A}\rightarrow\text{Extractor}^{S^{A}}$
where $T\triangleq S^{T}$} & {\footnotesize{}$\text{Extractor}^{T}$}\tabularnewline
\hline 
\end{tabular}
\par\end{centering}
\caption{Type constructions producing the \lstinline!Extractor! typeclass.\label{tab:Type-constructions-for-Extractor}}
\end{table}


\subsection{Equality comparison \textemdash{} the \texttt{Eq} typeclass\label{subsec:The-Eq-typeclass}}

In Scala, the built-in operation \lstinline!==! is not type-safe
because the code \lstinline!x == y! will compile regardless of the
types of \lstinline!x! and \lstinline!y!. We can replace \lstinline!==!
by a new operation \lstinline!===! constrained to a typeclass called
\lstinline!Eq!, ensuring that types can be meaningfully compared
for equality. The equality comparison for values of type $A$ is a
function of type $A\times A\rightarrow\bbnum 2$ (where $\bbnum 2$
denotes the \lstinline!Boolean! type). Typeclass instances of \lstinline!Eq!
need to wrap a function of that type. We also define \lstinline!===!
as an extension method:\index{typeclass!Eq@\texttt{Eq}}
\begin{lstlisting}
final case class Eq[A](equal: (A, A) => Boolean)
object Eq {
  implicit class EqOps[A: Eq](a: A) {
    def ===(b: A): Boolean = implicitly[Eq[A]].equal(a, b)
  } // Use type-specific comparisons to define some typeclass instances here:
  implicit val eqInt: Eq[Int] = Eq[Int](_ == _)
  implicit val eqString: Eq[String] = Eq[String](_ == _)
}
\end{lstlisting}
If we define an \lstinline!Eq! typeclass instance for all types via
the built-in \lstinline!==! operation, we will find that this operation
does not work as expected when comparing values of a function type,
e.g., \lstinline!Int => Int!: 
\begin{lstlisting}
import Eq._
implicit def eqTypeA[A] = Eq[A](_ == _)

scala> ((n: Int) => n) === ((n: Int) => n)
res1: Boolean = false 
\end{lstlisting}
Our expectations about equality comparisons are formalized via the
laws of identity, symmetry, reflexivity, and transitivity (see also
a discussion on page~\pageref{par:label-equality-laws} in Section~\ref{subsec:Examples-of-non-functors}).
The \textbf{reflexivity}\index{reflexivity law} law states that $x=x$
for any $x$; so the comparison \lstinline!x === x! should always
return \lstinline!true!. The example shown above violates that law
when we choose $x\triangleq n^{:\text{Int}}\rightarrow n$.

Let us perform structural analysis for the \lstinline!Eq! typeclass,
defining $\text{Eq}^{A}\triangleq A\times A\rightarrow\bbnum 2$.
The results (see Table~\ref{tab:Type-constructions-for-Eq} below)
will show which types can be usefully compared for equality.

\paragraph{Fixed types}

All primitive types have \lstinline!Eq! instances that use type-specific
equality comparisons.

\paragraph{Products}

If $A$ and $B$ have equality comparisons, we can compare pairs of
type $A\times B$ by comparing each part of the pair separately:
\begin{lstlisting}
def eqPair[A: Eq, B: Eq] = Eq[(A, B)]{ case ((a1, b1), (a2, b2)) => a1 === a2 && b1 === b2 }
\end{lstlisting}
It is easy to check that the identity, symmetry, reflexivity, and
transitivity laws hold for the new comparison operation if they hold
for comparisons of $A$ and $B$ separately.

It is important that the code for this construction assumes that both
types $A$ and $B$ have lawful \lstinline!Eq! instances and performs
the comparisons \lstinline!a1 === a2! and \lstinline!b1 === b2!.
If the above code performed only, say, the comparison \lstinline!a1 === a2!,
the resulting comparison operation would have violated the \index{identity laws!of equality}\textbf{identity
law} of the equality operation (if $x=y$ then $f(x)=f(y)$ for any
function $f$): we would have pairs such as $a\times b_{1}$ and $a\times b_{2}$
that would be \textsf{``}equal\textsf{''} according to this definition, and yet many
functions $f^{:A\times B\rightarrow C}$ exist such that $f(a\times b_{1})\neq f(a\times b_{2})$.

\paragraph{Co-products}

If $A$ and $B$ have equality comparisons, we can compare values
of type $A+B$ while ensuring that a value of type $A+\bbnum 0$ is
never equal to a value of type $\bbnum 0+B$:
\begin{lstlisting}[mathescape=true]
def eqEither[A: Eq, B: Eq] = Eq[Either[A, B]] {
  case (Left(a1), Left(a2))     => a1 === a2    // Compare $\color{dkgreen} a_1 + \bbnum0$ and $\color{dkgreen} a_2 + \bbnum0$.
  case (Right(b1), Right(b2))   => b1 === b2    // Compare $\color{dkgreen} \bbnum0 + b_1$ and $\color{dkgreen} \bbnum0 + b_2$.
  case _                        => false    // $\color{dkgreen} a + \bbnum0$ is never equal to $\color{dkgreen} \bbnum0 + b$.
}
\end{lstlisting}
The laws hold for the new operation because the code defines values
of type \lstinline!Either[A, B]! as equal only when the types are
both \lstinline!Left! or both \lstinline!Right!. If the comparisons
of types $A$ and $B$ satisfy the laws separately, the laws for $A+B$
will be satisfied separately for values of type \lstinline!Left!
and of type \lstinline!Right!.

Defining the comparison operation in any other way (e.g., setting
$a_{1}+\bbnum 0\neq a_{2}+\bbnum 0$ for all $a_{1}^{:A}$ and $a_{2}^{:A}$,
or $\bbnum 0+b_{1}=\bbnum 0+b_{2}$ for all $b_{1}^{:B}$ and $b_{2}^{:B}$)
would have violated the \index{reflexivity law}reflexivity law or
the identity law.

Since the \lstinline!Eq! typeclass has both the product and the co-product
constructions, any polynomial type expression made of primitive types
will also have an \lstinline!Eq! typeclass instance.

\paragraph{Functions}

If $A$ has an \lstinline!Eq! instance, can we create an \lstinline!Eq!
instance for $R\rightarrow A$ where $R$ is some other type? This
would be possible with a function of type
\begin{equation}
\forall A.\,(A\times A\rightarrow\bbnum 2)\rightarrow\left(R\rightarrow A\right)\times\left(R\rightarrow A\right)\rightarrow\bbnum 2\quad.\label{eq:type-signature-function-comparison}
\end{equation}
Here we assume that the type $R$ is an arbitrary chosen type, so
no values of type $R$ can be computed from scratch. (This would not
be the case when $R=\bbnum 1$ or $R=\bbnum 2$, say. But in those
cases the type $R\rightarrow A$ can be simplified to a polynomial
type, e.g., $\bbnum 1\rightarrow A\cong A$ and $\bbnum 2\rightarrow A\cong A\times A$,
etc.) Without values of type $R$, we cannot compute any values of
type $A$ and cannot apply comparisons to them. Then the only possible
implementations of the type signature~(\ref{eq:type-signature-function-comparison})
are constant functions returning \lstinline!true! or \lstinline!false!.
However, the implementation that always returns \lstinline!false!
will violate the reflexivity law $x=x$. The implementation that always
returns \lstinline!true! is not useful.

We will be able to evaluate functions of type $R\rightarrow A$ if
some chosen values of type $R$ are available. Examples of that situation
are types $R$ of the form $R\cong\bbnum 1+S$ for some type $S$;
we then always have a chosen value $r_{1}\triangleq1+\bbnum 0^{:S}$
of type $R$. What if we compare functions only via their values at
$r_{1}$?
\begin{lstlisting}
def equals[R, A: Eq](f: R => A, g: R => A): Boolean = f(r1) === g(r1)  // Violates the identity law.
\end{lstlisting}
The above code defines a comparison operation that violates the identity
law: there are many functions \lstinline!f! and \lstinline!g! that
will give different results for arguments not equal to $r_{1}$. 

Another way to see the problem is to write the type equivalence
\[
R\rightarrow A\cong\bbnum 1+S\rightarrow A\cong A\times(S\rightarrow A)\quad,
\]
which reduces this case to the product construction we saw above.
It follows that we need to have an \lstinline!Eq! instance for $S\rightarrow A$
to define the equality operation for $R\rightarrow A$. If we have
a chosen value of type $S$, e.g., if $S\cong\bbnum 1+T$, we will
again reduce the situation to the product construction with the function
type $T\rightarrow A$. This process will end only if the type $R$
has the form 
\[
R\cong\bbnum 1+\bbnum 1+...+\bbnum 1\quad,\quad\quad R\rightarrow A\cong\bbnum 1+\bbnum 1+...+\bbnum 1\rightarrow A\cong A\times A\times...\times A\quad,
\]
i.e., if $R$ has a \emph{known} finite number of distinct values.
Then we can write code that applies functions of type $R\rightarrow A$
to every possible value of the argument of type $R$ and compares
all the resulting values of type $A$. However, we also see that the
type $R\rightarrow A$ is equivalent to a polynomial type, which is
a product of a fixed number of $A$\textsf{'}s. The product construction already
covers that type.

So, we can compare functions $f_{1}^{:R\rightarrow A}$ and $f_{2}^{:R\rightarrow A}$
only if we are able to check whether $f_{1}(r)=f_{2}(r)$ for \emph{every}
possible value of type $R$. We cannot implement such a comparison
for a general type $R$.

We conclude that functions of type $R\rightarrow A$ cannot have an
\lstinline!Eq! instance for a general type $R$. A similar argument
shows that functions of type $A\rightarrow R$ also cannot have a
useful \lstinline!Eq! instance. The only exceptions are types $R\rightarrow A$
or $A\rightarrow R$ that are equivalent to some polynomial types.

\paragraph{Recursive types}

Since all polynomial type expressions preserve \lstinline!Eq! instances,
the same logic can be applied to recursive polynomial types. For instance,
lists and trees with \lstinline!Eq!-comparable values are also \lstinline!Eq!-comparable.
Let us prove this rigorously.

Consider a recursive polynomial type $T$ defined using a polynomial
functor $S^{\bullet}$,
\[
T\triangleq S^{T}\quad.
\]
The functor $S^{\bullet}$ may use other fixed types that have \lstinline!Eq!
instances. To construct the typeclass instance for $T$, we first
implement a function $\text{eqS}$ of type
\[
\text{eqS}:\text{Eq}^{A}\rightarrow\text{Eq}^{S^{A}}\quad.
\]
This function produces an \lstinline!Eq! instance for $S^{A}$ using
\lstinline!Eq! instances of $A$ and of all other types that $S^{A}$
depends on. The product and co-product constructions guarantee that
it is always possible to implement this function for a polynomial
functor $S^{\bullet}$. Then we define an \lstinline!Eq! instance
for $T$ recursively:
\[
\text{eqT}:\text{Eq}^{T}\quad,\quad\quad\text{eqT}\triangleq\text{eqS}\,(\text{eqT})\quad.
\]
The recursive equation for \lstinline!eqT! needs to be implemented
as an expanded function, 
\[
\text{eqT}\triangleq t^{:T}\times t^{:T}\rightarrow\text{eqS}\,(\text{eqT})\left(t\times t\right)\quad,
\]
and then, as we have seen in the previous section, the recursion will
terminate.

As an example, let us define an \lstinline!Eq! instance for the type
$T$ defined by $T\triangleq\text{Int}+T+\text{Int}\times T\times T$.
\begin{lstlisting}[mathescape=true]
type S[A] = Either[Either[Int, A], (Int, (A, A))]
final case class T(s: S[T])                     // Recursive type equation $\color{dkgreen} T\triangleq\text{Int}+T+\text{Int}\times T\times T $.
def eqS[A](implicit ti: Eq[A]): Eq[S[A]] = {    // Function of type Eq[A] => Eq[S[A]].
  implicit val e1 = eqEither[Int, A]            // Instance for $\color{dkgreen} \text{Int}+A $.
  implicit val e2 = eqPair[A, A]                // Instance for $\color{dkgreen} A\times A $.
  implicit val e3 = eqPair[Int, (A, A)]         // Instance for $\color{dkgreen} \text{Int}\times A\times A $.
  eqEither[Either[Int, A], (Int, (A, A))]       // Instance for $\color{dkgreen} \text{Int}+A+\text{Int}\times A\times A $.
}
implicit def eqT: Eq[T] = Eq { case (T(s1), T(s2)) => eqS(eqT).equal(s1, s2) }
\end{lstlisting}
To test that the recursion terminates, define a value of type $T$
and run a comparison:
\begin{lstlisting}[mathescape=true]
val t = T(Left(Right(T(Left(Left(10))))))   // $\color{dkgreen}t: \bbnum 0+(10^{\scriptscriptstyle:\text{Int}}+\bbnum 0+\bbnum 0)^{\scriptscriptstyle:T}+\bbnum 0$

scala> t === t
res0: Boolean = true
\end{lstlisting}


\paragraph{Checking laws for recursive instances}

We use induction to verify that the laws of identity, symmetry, reflexivity,
and transitivity will hold for the \lstinline!Eq! instance just defined.
The \lstinline!Eq! instance for $T$ was defined as a recursive function
\lstinline!eqT = eqS(eqT)!. We know that \lstinline!eqS(x)! satisfies
all the required laws if \lstinline!x! satisfies them (\textsf{``}\lstinline!eqS!
preserves the laws\textsf{''}). Let us visualize what happens when the function
\lstinline!eqT! is applied to some values of type $T$. Are the laws
satisfied in that case (e.g., is \lstinline!eqT(t, t) == true! for
all \lstinline!t:T!)? The function \lstinline!eqT! will call itself
recursively whenever the body of \lstinline!eqS! calls \lstinline!eqT!.
\emph{Assuming} that all the recursive calls to \lstinline!eqT! satisfy
the laws, we find that the outer call to \lstinline!eqT! also satisfies
the laws because \lstinline!eqS! preserves them. This corresponds
to the inductive step.

Eventually the recursion will terminate; so \emph{some} calls of \lstinline!eqT(t1, t2)!
with certain values \lstinline!t1! and \lstinline!t2! do not cause
any more recursive self-calls to \lstinline!eqT!. For \emph{those}
values \lstinline!t1! and \lstinline!t2!, the function \lstinline!eqT!
will satisfy the required laws with no additional assumptions, because
\lstinline!eqS(eqT)(t1, t2)!, which satisfies the laws, does not
call \lstinline!eqT!. This corresponds to the base case of an inductive
proof. 

So, the recursively defined \lstinline!Eq! instance is lawful. This
argument is general and works in all cases when a typeclass instance
$t$ is defined by recursion, $t\triangleq s(t)$, via a function
$s$ that preserves the laws.

\paragraph{Summary}

Instances of the \lstinline!Eq! typeclass can be derived for any
polynomial or recursive polynomial type expressions containing primitive
types or type parameters constrained to be \lstinline!Eq!-comparable.
The derivation of the \lstinline!Eq! instance is unambiguous and
can be automated with libraries such as the \texttt{kittens}\footnote{\texttt{\href{https://github.com/typelevel/kittens}{https://github.com/typelevel/kittens}}},
\texttt{magnolia}\footnote{\texttt{\href{https://github.com/propensive/magnolia}{https://github.com/propensive/magnolia}}}
, or \texttt{scalaz-deriving}\footnote{\texttt{\href{https://github.com/scalaz/scalaz-deriving}{https://github.com/scalaz/scalaz-deriving}}}.

\begin{table}
\begin{centering}
\begin{tabular}{|c|c|c|}
\hline 
\textbf{\footnotesize{}Construction} & \textbf{\footnotesize{}Type signature to implement} & \textbf{\footnotesize{}Results}\tabularnewline
\hline 
\hline 
{\footnotesize{}The }\lstinline!Unit!{\footnotesize{} type, or other
primitive type} & {\footnotesize{}$\text{Eq}^{T}\triangleq T\times T\rightarrow\bbnum 2$} & {\footnotesize{}the method }\lstinline!==!\tabularnewline
\hline 
{\footnotesize{}Product of }\lstinline!Eq!{\footnotesize{} types
$A$ and $B$} & {\footnotesize{}$\text{Eq}^{A}\times\text{Eq}^{B}\rightarrow\text{Eq}^{A\times B}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Co-product of }\lstinline!Eq!{\footnotesize{} types
$A$ and $B$} & {\footnotesize{}$\text{Eq}^{A}\times\text{Eq}^{B}\rightarrow\text{Eq}^{A+B}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Recursive types} & {\footnotesize{}$\text{Eq}^{A}\rightarrow\text{Eq}^{S^{A}}$ where
$T\triangleq S^{T}$} & {\footnotesize{}$\text{Eq}^{T}$}\tabularnewline
\hline 
\end{tabular}
\par\end{centering}
\caption{Type constructions producing the \lstinline!Eq! typeclass.\label{tab:Type-constructions-for-Eq}}
\end{table}


\subsection{Semigroups\label{subsec:Semigroups-constructions}}

A type $T$ has an instance of \lstinline!Semigroup! when an associative
binary operation of type $T\times T\rightarrow T$ is available. We
will now apply structural analysis to this typeclass. The results
are shown in Table~\ref{tab:Type-constructions-for-semigroup}.

\paragraph{Fixed types}

Each of the primitive types (\lstinline!Boolean!, \lstinline!Int!,
\lstinline!Double!, \lstinline!String!, etc.) has at least one well-known
associative binary operation that can be used to define a semigroup
instance. Booleans have the conjunction and the disjunction operations;
numbers can be added or multiplied, or the maximum or the minimum
number chosen; strings can be concatenated or chosen in the alphabetical
order. Examples~\ref{subsec:tc-Example-Semigroups} and~\ref{subsec:tc-Example-semigroup-alternative-implementations}
show several implementations of such binary operations. The \lstinline!Unit!
type has a trivially defined binary operation, which is also associative
(since it always returns the same value). The same is true for any
fixed type that has a chosen \textsf{``}default\textsf{''} value: the binary operation
that always returns the default value is associative (although not
likely to be useful).

\paragraph{Type parameters}

A semigroup instance parametric in type $T$ means a value of type
$\forall T.\,T\times T\rightarrow T$. There are two implementations
of this type signature: $a^{:T}\times b^{:T}\rightarrow a$ and $a^{:T}\times b^{:T}\rightarrow b$.
Both provide an associative binary operation, as Example~\ref{subsec:tc-Example-semigroup-alternative-implementations}(a)
shows. So, any type $T$ can be made into a \textsf{``}trivial\textsf{''} semigroup
in one of these two ways. (\index{trivial@\textsf{``}trivial\textsf{''} semigroup}\textsf{``}Trivial\textsf{''}
semigroups are occasionally useful.)

\paragraph{Products}

If types $A$ and $B$ are semigroups, the product $A\times B$ can
be also given a \lstinline!Semigroup! instance. 

To compute that instance means, in the general case, to implement
a function with type
\[
\text{semigroupPair}:\forall(A,B).\,\text{Semigroup}^{A}\times\text{Semigroup}^{B}\rightarrow\text{Semigroup}^{A\times B}\quad.
\]
Writing out the type expressions, we get the type signature
\[
\text{semigroupPair}:\forall(A,B).\,\left(A\times A\rightarrow A\right)\times\left(B\times B\rightarrow B\right)\rightarrow\left(A\times B\times A\times B\rightarrow A\times B\right)\quad.
\]
While this type signature can be implemented in a number of ways,
we look for code that preserves information, in hopes of satisfying
the associativity law. The code should be a function of the form
\[
\text{semigroupPair}\triangleq f^{:A\times A\rightarrow A}\times g^{:B\times B\rightarrow B}\rightarrow a_{1}^{:A}\times b_{1}^{:B}\times a_{2}^{:A}\times b_{2}^{:B}\rightarrow???^{:A}\times???^{:B}\quad.
\]
Since we are trying to define the new semigroup operation through
the previously given operations $f$ and $g$, it is natural to apply
$f$ and $g$ to the given data $a_{1}$, $a_{2}$, $b_{1}$, $b_{2}$
and write 
\[
f^{:A\times A\rightarrow A}\times g^{:B\times B\rightarrow B}\rightarrow a_{1}^{:A}\times b_{1}^{:B}\times a_{2}^{:A}\times b_{2}^{:B}\rightarrow f(a_{1},a_{2})\times g(b_{1},b_{2})\quad.
\]
This code defines a new binary operation $\oplus_{A\times B}$ via
the previously given $\oplus_{A}$ and $\oplus_{B}$ as
\begin{equation}
(a_{1}^{:A}\times b_{1}^{:B})\oplus_{A\times B}(a_{2}^{:A}\times b_{2}^{:B})=(a_{1}\oplus_{A}a_{2})\times(b_{1}\oplus_{B}b_{2})\quad.\label{eq:semigroup-product-operation-def}
\end{equation}
\begin{lstlisting}
def semigroupPair[A: Semigroup, B: Semigroup] =
  Semigroup[(A, B)]{ case ((a1, b1),(a2, b2)) => (a1 |+| a2, b1 |+| b2) }
\end{lstlisting}
This implementation satisfies the associativity law if the operations
$\oplus_{A}$, $\oplus_{B}$ already do, i.e., if the results of computing
$a_{1}\oplus_{A}a_{2}\oplus_{A}a_{3}$ and $b_{1}\oplus_{B}b_{2}\oplus_{B}b_{3}$
do not depend on the order of parentheses:
\begin{align*}
 & \left(\left(a_{1}\times b_{1}\right)\oplus_{A\times B}\left(a_{2}\times b_{2}\right)\right)\oplus_{A\times B}\left(a_{3}\times b_{3}\right)=\left((a_{1}\oplus_{A}a_{2})\times(b_{1}\oplus_{B}b_{2})\right)\oplus_{A\times B}\left(a_{3}\times b_{3}\right)\\
 & \quad\quad=\left(a_{1}\oplus_{A}a_{2}\oplus_{A}a_{3}\right)\times\left(b_{1}\oplus_{B}b_{2}\oplus_{B}b_{3}\right)\quad,\\
 & \left(a_{1}\times b_{1}\right)\oplus_{A\times B}\left(\left(a_{2}\times b_{2}\right)\oplus_{A\times B}\left(a_{3}\times b_{3}\right)\right)=\left(a_{1}\times b_{1}\right)\oplus_{A\times B}\left((a_{2}\oplus_{A}a_{3})\times(b_{2}\oplus_{B}b_{3})\right)\\
 & \quad\quad=\left(a_{1}\oplus_{A}a_{2}\oplus_{A}a_{3}\right)\times\left(b_{1}\oplus_{B}b_{2}\oplus_{B}b_{3}\right)\quad.
\end{align*}


\paragraph{Co-products}

To compute a \lstinline!Semigroup! instance for the co-product $A+B$
of two semigroups, we need
\[
\text{semigroupEither}:\forall(A,B).\,\text{Semigroup}^{A}\times\text{Semigroup}^{B}\rightarrow\text{Semigroup}^{A+B}\quad.
\]
Writing out the type expressions, we get the type signature
\[
\text{semigroupEither}:\forall(A,B).\,\left(A\times A\rightarrow A\right)\times\left(B\times B\rightarrow B\right)\rightarrow\left(A+B\right)\times\left(A+B\right)\rightarrow A+B\quad.
\]
Begin by writing a function with a typed hole:
\[
\text{semigroupEither}\triangleq f^{:A\times A\rightarrow A}\times g^{:B\times B\rightarrow B}\rightarrow c^{:\left(A+B\right)\times\left(A+B\right)}\rightarrow\text{???}^{:A+B}\quad.
\]
Transforming the type expression $\left(A+B\right)\times\left(A+B\right)$
into an equivalent disjunctive type,
\[
\left(A+B\right)\times\left(A+B\right)\cong A\times A+A\times B+B\times A+B\times B\quad,
\]
we can continue to write the function\textsf{'}s code in matrix notation,
\[
f^{:A\times A\rightarrow A}\times g^{:B\times B\rightarrow B}\rightarrow\,\begin{array}{|c||cc|}
 & A & B\\
\hline A\times A & \text{???}^{:A\times A\rightarrow A} & \text{???}^{:A\times A\rightarrow B}\\
A\times B & \text{???}^{:A\times B\rightarrow A} & \text{???}^{:A\times B\rightarrow B}\\
B\times A & \text{???}^{:B\times A\rightarrow A} & \text{???}^{:B\times A\rightarrow B}\\
B\times B & \text{???}^{:B\times B\rightarrow A} & \text{???}^{:B\times B\rightarrow B}
\end{array}\quad.
\]
The matrix is $4\times2$ because the input type, $A\times A+A\times B+B\times A+B\times B$,
is a disjunction with $4$ parts, while the result type $A+B$ is
a disjunction with $2$ parts. In each row, we need to fill only one
of the two typed holes because only one part of the disjunction $A+B$
can have a value.

To save space, we will omit the types in the matrices. The first and
the last rows of the matrix must contain functions of types $A\times A\rightarrow A$
and $B\times B\rightarrow B$, and so it is natural to fill them with
$f$ and $g$:
\[
f^{:A\times A\rightarrow A}\times g^{:B\times B\rightarrow B}\rightarrow\,\begin{array}{||cc|}
f^{:A\times A\rightarrow A} & \bbnum 0\\
\text{???}^{:A\times B\rightarrow A} & \text{???}^{:A\times B\rightarrow B}\\
\text{???}^{:B\times A\rightarrow A} & \text{???}^{:B\times A\rightarrow B}\\
\bbnum 0 & g^{:B\times B\rightarrow B}
\end{array}\quad.
\]
The remaining two rows can be filled in four different ways:
\begin{align*}
f\times g\rightarrow\,\begin{array}{||cc|}
f^{:A\times A\rightarrow A} & \bbnum 0\\
a^{:A}\times b^{:B}\rightarrow a & \bbnum 0\\
b^{:B}\times a^{:A}\rightarrow a & \bbnum 0\\
\bbnum 0 & g^{:B\times B\rightarrow B}
\end{array}~\quad,\quad\quad & ~f\times g\rightarrow\,\begin{array}{||cc|}
f & \bbnum 0\\
\bbnum 0 & a^{:A}\times b^{:B}\rightarrow b\\
\bbnum 0 & b^{:B}\times a^{:A}\rightarrow b\\
\bbnum 0 & g
\end{array}\quad,\\
f\times g\rightarrow\,\begin{array}{||cc|}
f^{:A\times A\rightarrow A} & \bbnum 0\\
\bbnum 0 & a^{:A}\times b^{:B}\rightarrow b\\
b^{:B}\times a^{:A}\rightarrow a & \bbnum 0\\
\bbnum 0 & g^{:B\times B\rightarrow B}
\end{array}\quad,\quad\quad & f\times g\rightarrow\,\begin{array}{||cc|}
f & \bbnum 0\\
a^{:A}\times b^{:B}\rightarrow a & \bbnum 0\\
\bbnum 0 & b^{:B}\times a^{:A}\rightarrow b\\
\bbnum 0 & g
\end{array}\quad.
\end{align*}
The Scala code corresponding to the four possible definitions of $\oplus$
is
\begin{lstlisting}[mathescape=true]
def semigroupEither1[A: Semigroup, B: Semigroup] = Semigroup[Either[A, B]] {
  case (Left(a1), Left(a2))     =>  a1 |+| a2 // Here a1 |+| a2 is $\color{dkgreen} a_1 \oplus_A a_2 $.
  case (Right(b1), Right(b2))   =>  b1 |+| b2 // Here b1 |+| b2 is $\color{dkgreen} b_1 \oplus_B b_2$.
  case (Left(a), Right(b))      =>  a         // "Take $\color{dkgreen}A$" - discard all data of type $\color{dkgreen}B$.
  case (Right(b), Left(a))      =>  a
}
def semigroupEither2[A: Semigroup, B: Semigroup] = Semigroup[Either[A, B]] {
  case (Left(a1), Left(a2))     =>  a1 |+| a2
  case (Right(b1), Right(b2))   =>  b1 |+| b2
  case (Left(a), Right(b))      =>  b         // "Take $\color{dkgreen}B$" - discard all data of type $\color{dkgreen}A$.
  case (Right(b), Left(a))      =>  b
}
def semigroupEither3[A: Semigroup, B: Semigroup] = Semigroup[Either[A, B]] {
  case (Left(a1), Left(a2))     =>  a1 |+| a2
  case (Right(b1), Right(b2))   =>  b1 |+| b2
  case (Left(a), Right(b))      =>  a         // "Take first" - discard ${\color{dkgreen}y}$ in ${\color{dkgreen}x\oplus y}$.
  case (Right(b), Left(a))      =>  b
}
def semigroupEither4[A: Semigroup, B: Semigroup] = Semigroup[Either[A, B]] {
  case (Left(a1), Left(a2))     =>  a1 |+| a2
  case (Right(b1), Right(b2))   =>  b1 |+| b2
  case (Left(a), Right(b))      =>  b         // "Take last" - discard ${\color{dkgreen}x}$ in ${\color{dkgreen}x\oplus y}$.
  case (Right(b), Left(a))      =>  a
}
\end{lstlisting}
The four different choices of the binary operation can be described
as:

1. (\textsf{``}Take $A$\textsf{''}) Discard all data of type $B$: $(a^{:A}+\bbnum 0)\oplus(\bbnum 0+b^{:B})=a$
and $(\bbnum 0+b^{:B})\oplus(a^{:A}+\bbnum 0)=a$.

2. (\textsf{``}Take $B$\textsf{''}) Discard all data of type $A$: $(a^{:A}+\bbnum 0)\oplus(\bbnum 0+b^{:B})=b$
and $(\bbnum 0+b^{:B})\oplus(a^{:A}+\bbnum 0)=b$.

3. (\textsf{``}Take first\textsf{''}) $x\oplus y$ discards $y$: $(a^{:A}+\bbnum 0)\oplus(\bbnum 0+b^{:B})=a$
and $(\bbnum 0+b^{:B})\oplus(a^{:A}+\bbnum 0)=b$.

4. (\textsf{``}Take last\textsf{''}) $x\oplus y$ discards $x$: $(a^{:A}+\bbnum 0)\oplus(\bbnum 0+b^{:B})=b$
and $(\bbnum 0+b^{:B})\oplus(a^{:A}+\bbnum 0)=a$.

\noindent Does the semigroup law~(\ref{eq:associativity-law-semigroup})
hold for the new typeclass instance with any of these implementations?

It turns out that \emph{all} \emph{four} implementations are lawful.
To verify the associativity law, we need to show that values such
as \lstinline!Left(x) |+| Left(y) |+| Right(z)! or \lstinline!Left(x) |+| Right(y) |+| Right(z)!
do not depend on the order of inserted parentheses. Expressions of
the form $x\oplus y\oplus z$ can have $8$ possible combinations
of \lstinline!Left! and \lstinline!Right! types. Each of them needs
to be checked against each of the $4$ implementations of $\oplus$.
Instead of doing $32$ separate derivations, we will reason case by
case.

First consider the case when all three values are of type \lstinline!Left(x)!.
In all four implementations, the binary operation reduces to the binary
operation of the semigroup $A$, which is associative since we assume
that $A$ is a lawful semigroup:
\begin{lstlisting}
Left(x) |+| Left(y) |+| Left(z) == Left(x |+| y |+| z) == Left(x) |+| ( Left(y) |+| Left(z) )
\end{lstlisting}

The same argument applies to three values of type \lstinline!Right!.
It remains to consider the \textsf{``}mixed\textsf{''} cases.

In the first implementation (\textsf{``}take $A$\textsf{''}), we discard all data
of type \lstinline!Right! from the expression $x\oplus y\oplus z$,
keeping only data of type \lstinline!Left!. It is clear that discarding
data of type \lstinline!Right! will yield the same result regardless
of the order of parentheses. If more than one item of type \lstinline!Left!
remains, the data is aggregated with the operation $\oplus_{A}$.
So, the results do not depend on the order of parentheses:
\begin{lstlisting}
Right(x) |+| Right(y) |+| Left(z) == Left(z) == Right(x) |+| ( Right(y) |+| Left(z) )
Left(x) |+| Right(y) |+| Left(z) == Left(x |+| z) == Left(x) |+| ( Right(y) |+| Left(z) )
\end{lstlisting}

A similar argument shows that the second implementation (\textsf{``}take $B$\textsf{''})
is also associative.

The implementation \textsf{``}take first\textsf{''} will select the first value whenever
the types are mixed. Therefore
\begin{lstlisting}[mathescape=true]
Left(x) |+| Left(y) |+| Right(z) == Left(x |+| y) == Left(x) |+| ( Left(y) |+| Right(z) )
Left(x) |+| Right(y) |+| p == Left(x) == Left(x) |+| ( Right(y) |+| p )    // Regardless of p.
Right(x) |+| Left(y) |+| p == Right(x) == Right(x) |+| ( Left(y) |+| p )   // Regardless of p.
Right(x) |+| Right(y) |+| Left(z) == Right(x |+| y) == Right(x) |+| ( Right(y) |+| Left(z) )
\end{lstlisting}
The results are independent of the parentheses. The same applies to
the \textsf{``}take last\textsf{''} implementation.

\paragraph{Functions}

If $A$ is a semigroup and $E$ is any fixed type, are the types $A\rightarrow E$
and/or $E\rightarrow A$ semigroups? To create a \lstinline!Semigroup!
instance for $E\rightarrow A$ means to implement the type signature
\[
\text{Semigroup}^{A}\rightarrow\text{Semigroup}^{E\rightarrow A}=\left(A\times A\rightarrow A\right)\rightarrow\left(E\rightarrow A\right)\times\left(E\rightarrow A\right)\rightarrow E\rightarrow A\quad.
\]
An implementation that preserves information is
\[
\text{semigroupFunc}\triangleq f^{:A\times A\rightarrow A}\rightarrow g_{1}^{:E\rightarrow A}\times g_{2}^{:E\rightarrow A}\rightarrow e^{:E}\rightarrow f(g_{1}(e),g_{2}(e))\quad.
\]
This defines the new $\oplus$ operation by $g_{1}\oplus g_{2}\triangleq e\rightarrow g_{1}(e)\oplus_{A}g_{2}(e)$.
\begin{lstlisting}
def semigroupFunc[E, A: Semigroup] = Semigroup[E => A] { case (g1, g2) => e => g1(e) |+| g2(e) }
\end{lstlisting}

In the pipe notation, $e\triangleright(f\oplus g)=f(e)\oplus_{A}g(e)$.
The associativity law holds for this operation:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & e\triangleright\left(\left(f\oplus g\right)\oplus h\right)=\left(e\triangleright(f\oplus g)\right)\oplus_{A}h(e)=f(e)\oplus_{A}g(e)\oplus_{A}h(e)\quad.\\
{\color{greenunder}\text{right-hand side}:}\quad & e\triangleright\left(f\oplus\left(g\oplus h\right)\right)=f(e)\oplus_{A}\left(e\triangleright(g\oplus h)\right)=f(e)\oplus_{A}g(e)\oplus_{A}h(e)\quad.
\end{align*}

The type $A\rightarrow E$ only allows semigroup operations that discard
the left or the right element: the type signature $f^{:A\times A\rightarrow A}\rightarrow h_{1}^{:A\rightarrow E}\times h_{2}^{:A\rightarrow E}\rightarrow\text{???}^{:A\rightarrow E}$
can be implemented only by discarding $f$ and one of $h_{1}$ or
$h_{2}$. Either choice makes $A\rightarrow E$ into a trivial semigroup.

We have seen constructions that create new semigroups via products,
co-products, and functions. Thus, any exponential-polynomial type
expression built up from primitive types and/or existing semigroups
is again a semigroup.

\paragraph{Recursive types}

A type $T$ defined by a recursive type equation $T\triangleq S^{T}$
can have a semigroup instance when $S^{A}$ is any exponential-polynomial
type expression built up from primitive types, products, co-products,
and the type parameter $A$. The known semigroup constructions guarantee
that a typeclass instance \lstinline!Semigroup[S[A]]! can be created
out of \lstinline!Semigroup[A]!. This gives us a function 
\[
\text{semigroupS}:\text{Semigroup}^{A}\rightarrow\text{Semigroup}^{S^{A}}\quad.
\]
Then a semigroup instance for $T$ is defined recursively as
\[
\text{semigroupT}\triangleq\text{semigroupS}\,(\text{semigroupT})\quad.
\]
The recursive definition will terminate as long as we implement it
in code as an expanded function. The associativity law holds for the
semigroup $T$ by induction, as shown at the end of Section~\ref{subsec:The-Eq-typeclass}.

\paragraph{Summary}

Any type expression whatsoever can have a \lstinline!Semigroup! instance.
Since the instances have several inequivalent implementations, automatic
derivation of \lstinline!Semigroup! instances is not often useful.

\begin{table}
\begin{centering}
\begin{tabular}{|c|c|c|}
\hline 
\textbf{\footnotesize{}Construction} & \textbf{\footnotesize{}Type signature to implement} & \textbf{\footnotesize{}Results}\tabularnewline
\hline 
\hline 
{\footnotesize{}The }\lstinline!Unit!{\footnotesize{} type, or other
fixed type $C$} & {\footnotesize{}$\text{Semigroup}^{C}$} & {\footnotesize{}two trivial semigroups}\tabularnewline
\hline 
{\footnotesize{}Product of semigroups $A$ and $B$} & {\footnotesize{}$\text{Semigroup}^{A}\times\text{Semigroup}^{B}\rightarrow\text{Semigroup}^{A\times B}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Co-product of semigroups $A$ and $B$} & {\footnotesize{}$\text{Semigroup}^{A}\times\text{Semigroup}^{B}\rightarrow\text{Semigroup}^{A+B}$} & {\footnotesize{}four possibilities}\tabularnewline
\hline 
{\footnotesize{}Function from another type $E$} & {\footnotesize{}$\text{Semigroup}^{A}\rightarrow\text{Semigroup}^{E\rightarrow A}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Recursive type} & {\footnotesize{}$\text{Semigroup}^{A}\rightarrow\text{Semigroup}^{S^{A}}$
where $T\triangleq S^{T}$} & {\footnotesize{}$\text{Semigroup}^{T}$}\tabularnewline
\hline 
\end{tabular}
\par\end{centering}
\caption{Type constructions producing the \lstinline!Semigroup! typeclass.\label{tab:Type-constructions-for-semigroup}}
\end{table}


\subsection{Monoids\label{subsec:Monoids-constructions}}

Since a monoid is a semigroup with a default value, a \lstinline!Monoid!
instance is a value of type
\[
\text{Monoid}^{A}\triangleq\left(A\times A\rightarrow A\right)\times A\quad.
\]
For the binary operation $A\times A\rightarrow A$, we can re-use
the results of structural analysis for semigroups. Additionally, we
will need to verify that the default value satisfies monoid\textsf{'}s identity
laws. The results are shown in Table~\ref{tab:Type-constructions-for-monoid}.

\paragraph{Fixed types}

Each of the primitive types (\lstinline!Boolean!, \lstinline!Int!,
\lstinline!Double!, \lstinline!String!, etc.) has a well-defined
monoidal operation (addition or multiplication for numbers, concatenation
for strings, and so on). The unit type, $\bbnum 1$, also has a monoid
instance where all methods return the unit value $1$.

\paragraph{Type parameters}

This construction works for semigroups but \emph{not} for monoids:
the \textsf{``}trivial\textsf{''} semigroup operations $x\oplus y=x$ and $x\oplus y=y$
are not compatible with monoid\textsf{'}s identity laws. (e.g., with the definition
$x\oplus y=x$, no default value $e$ could possibly satisfy the left
identity law $e\oplus y=y$ because $e\oplus y=e$ for all $y$).

\paragraph{Products}

For two monoids $A$ and $B$, a monoid instance for the product $A\times B$
is computed by
\[
\text{monoidPair}:\forall(A,B).\,\text{Monoid}^{A}\times\text{Monoid}^{B}\rightarrow\text{Monoid}^{A\times B}\quad.
\]
The empty value for the monoid $A\times B$ is $e_{A\times B}\triangleq e_{A}\times e_{B}$,
the pair of empty values from the monoids $A$ and $B$. The new binary
operation is defined by Eq.~(\ref{eq:semigroup-product-operation-def})
as in the pair semigroup construction. We can now verify the new monoid\textsf{'}s
identity laws, assuming that they hold for the monoids $A$ and $B$:
\begin{align*}
(a_{1}\times b_{1})\oplus(e_{A}\times e_{B}) & =(a_{1}\oplus_{A}e_{A})\times(b_{1}\oplus_{B}e_{B})=a_{1}\times b_{1}\quad,\\
(e_{A}\times e_{B})\oplus(a_{2}\times b_{2}) & =(e_{A}\oplus_{A}a_{2})\times(e_{B}\oplus_{B}b_{2})=a_{2}\times b_{2}\quad.
\end{align*}
An implementation in Scala is

\begin{lstlisting}
def monoidPair[A: Monoid, B: Monoid]: Monoid[(A, B)] = Monoid[(A, B)](
  { case ((a1, b1),(a2, b2)) => (a1 |+| a2, b1 |+| b2) },
  ( implicitly[Monoid[A]].empty, implicitly[Monoid[B]].empty )
)
\end{lstlisting}

\begin{comment}
A special case of a product construction is the \textsf{``}twisted product\textsf{''}
$S\times P$ where $S$ is a semigroup that has an \textbf{action
on} $P$. The \textsf{``}action\textsf{''} is a function $\alpha:S\rightarrow P\rightarrow P$
such that $\alpha(s_{1})\bef\alpha(s_{2})=\alpha(s_{1}\oplus s_{2})$.
The operation is defined as 
\[
(s_{1}\times p_{1})\oplus(s_{2}\times p_{2})=(s_{1}\oplus_{S}s_{2})\times\alpha(s_{2})(p_{1})\quad.
\]
Examples of this construction are $\left(A\rightarrow A\right)\times A$
and $\bbnum 2\times\left(\bbnum 1+A\right)$. This cannot be made
into a monoid since the information about $p_{2}$ is discarded. The
associativity law holds because the first part of the pair is associative
by assumption of semigroup $S$, and the second part of the pair is
\[
\alpha(s_{2}\oplus_{S}s_{3})(p_{1})=\alpha(s_{3})(\alpha(s_{2})(p_{1}))\quad.
\]
\end{comment}


\paragraph{Co-products}

For two monoids $A$ and $B$, how can we implement a \lstinline!Monoid!
instance for $A+B$? We have seen four versions of the semigroup operation
$\oplus$ for the type $A+B$. Independently of those, we need to
define the empty element $e_{A+B}$, which must have type $A+B$.
There are two possibilities: 
\[
e_{A+B}\triangleq e_{A}+\bbnum 0^{:B}\quad\quad\text{ or }\quad\quad e_{A+B}\triangleq\bbnum 0^{:A}+e_{B}\quad.
\]
It remains to see which of the eight combinations will satisfy the
monoid identity laws,
\begin{align*}
\left(a+\bbnum 0\right)\oplus e_{A+B} & =a+\bbnum 0\quad,\quad\quad e_{A+B}\oplus\left(a+\bbnum 0\right)=a+\bbnum 0\quad,\\
\left(\bbnum 0+b\right)\oplus e_{A+B} & =\bbnum 0+b\quad,\quad\quad e_{A+B}\oplus\left(\bbnum 0+b\right)=\bbnum 0+b\quad.
\end{align*}
First choose $e_{A+B}=e_{A}+\bbnum 0$; the reasoning for the other
case will be quite similar. The first line above,
\[
\left(a+\bbnum 0\right)\oplus\left(e_{A}+\bbnum 0\right)=a+\bbnum 0\quad,\quad\quad\left(e_{A}+\bbnum 0\right)\oplus\left(a+\bbnum 0\right)=a+\bbnum 0\quad,
\]
will hold because all four versions of the operation $\oplus$ will
reduce to $\oplus_{A}$ on values of type $A+\bbnum 0$. The second
line, however, is compatible only with one version of the $\oplus$
operation, namely with \textsf{``}take $B$\textsf{''}:
\[
(a^{:A}+\bbnum 0)\oplus(\bbnum 0+b^{:B})=b\quad\quad\text{ and }\quad\quad(\bbnum 0+b^{:B})\oplus(a^{:A}+\bbnum 0)=b\quad.
\]
So, the co-product construction must choose one of the monoids, say
$B$, as \textsf{``}preferred\textsf{''}. The code is
\begin{lstlisting}
def monoidEitherPreferB[A: Monoid, B: Monoid] = Monoid[Either[A, B]]( {
  case (Left(a1), Left(a2))     => Left(a1 |+| a2)
  case (Left(a), Right(b))      => Right(b) // "Take B".
  case (Right(b), Left(a))      => Right(b)
  case (Right(b1), Right(b2))   => Right(b1 |+| b2)
}, Left(implicitly[Monoid[A]].empty) )
\end{lstlisting}
Similarly, the choice $e_{A+B}\triangleq\bbnum 0+e_{B}$ forces us
to choose the version \textsf{``}take $A$\textsf{''} of the $\oplus$ operation.

\paragraph{Functions}

The semigroup construction for function types works also for monoids.
Exercise~\ref{subsec:tc-Exercise-3} will show that the function
type $R\rightarrow A$ is a lawful monoid for any type $R$ and any
monoid $A$.

Additionally, the function type $R\rightarrow R$ is a monoid for
any type $R$ (even if $R$ is not a monoid). The operation $\oplus$
and the empty value are defined as $f^{:R\rightarrow R}\oplus g^{:R\rightarrow R}\triangleq f\bef g$
and $e_{R\rightarrow R}\triangleq\text{id}^{R}$. The code is
\begin{lstlisting}
def monoidFunc1[R]: Monoid[R => R] = Monoid( (f, g) => f andThen g, identity )
\end{lstlisting}
The monoidal operation $\oplus$ is the forward function composition
$f\bef g$, so the monoid laws for this operation are the identity
and the associativity laws of function composition (see Section~\ref{subsec:Laws-of-function-composition}).

We could also define the monoidal operation as the backward function
composition, $f\circ g$. 

\paragraph{Recursive types}

Can we define a \lstinline!Monoid! instance for a type $T$ defined
by $T\triangleq S^{T}$, where $S^{\bullet}$ is some type constructor?
As we have seen, products, co-products, and function type constructions
preserve monoids. For any type built up via these constructions from
monoids, a \lstinline!Monoid! instance can be derived. These constructions
cover all exponential-polynomial types. So, let us consider an exponential-polynomial
type constructor $S^{A}$ that contains a type parameter $A$, primitive
types, and other known monoid types. For such type constructors $S^{\bullet}$,
we will always be able to implement a function \lstinline!monoidS!
that derives a \lstinline!Monoid! instance for $S^{A}$ from a monoid
instance for $A$:
\[
\text{monoidS}:\text{Monoid}^{A}\rightarrow\text{Monoid}^{S^{A}}\quad.
\]
A monoid instance for $T$ is then defined recursively by
\[
\text{monoidT}\triangleq\text{monoidS}\left(\text{monoidT}\right)\quad.
\]
As we saw before, the code for this definition will terminate only
if we implement it as a recursive function. However, the type $\text{Monoid}^{A}$
is not a function type: it is a pair $\left(A\times A\rightarrow A\right)\times A$.
To obtain a working implementation of \lstinline!monoidT!, we need
to rewrite that type into an equivalent function type,
\[
\text{Monoid}^{A}=\left(A\times A\rightarrow A\right)\times A\cong\left(A\times A\rightarrow A\right)\times\left(\bbnum 1\rightarrow A\right)\cong\left(\bbnum 1+A\times A\rightarrow A\right)\quad,
\]
where we used the known type equivalences $A\cong\bbnum 1\rightarrow A$
and $\left(A\rightarrow C\right)\times\left(B\rightarrow C\right)\cong A+B\rightarrow C$.
\begin{lstlisting}
final case class Monoid[A](methods: Option[(A, A)] => A)
\end{lstlisting}
With this new definition of the \lstinline!Monoid! typeclass (and
with the appropriate changes to the code of \lstinline!monoidPair!,
\lstinline!monoidEitherPreferB!, and \lstinline!monoidFunc!), we
can now implement the recursive construction.

To illustrate how that works, consider the exponential-polynomial
type constructor $S^{\bullet}$ defined as
\[
S^{A}\triangleq\left(\text{Int}+A\right)\times\text{Int}+\text{String}\times\left(A\rightarrow\left(A\rightarrow\text{Int}\right)\rightarrow A\right)\quad.
\]
\begin{lstlisting}
type S[A] = Either[(Either[Int, A], Int), (String, A => (A => Int) => A)]
\end{lstlisting}

It is clear that $S^{A}$ is built up from type constructions that
preserve monoids at each step. So, we expect that the recursive type
$T\triangleq S^{T}$ is a monoid. We first implement the function
\lstinline!monoidS!,
\begin{lstlisting}
def monoidS[A](implicit ti: Monoid[A]): Monoid[S[A]] = {
  implicit val m0 = monoidEitherPreferB[Int, A]
  implicit val m1 = monoidPair[Either[Int, A], Int]
  implicit val m2 = monoidFunc[A, A => Int]
  implicit val m3 = monoidFunc[(A => Int) => A, A]
  implicit val m4 = monoidPair[String, A => (A => Int) => A]
  monoidEitherPreferB[(Either[Int, A], Int), (String, A => (A => Int) => A)]
}
\end{lstlisting}
We can now use this function to define the recursive type $T$ and
a \lstinline!Monoid! instance for it,
\begin{lstlisting}
final case class T(s: S[T])
def monoidT: Monoid[T] = Monoid[T] {
  case None             => T(monoidS[T](monoidT).methods(None))
  case Some((t1, t2))   => T(monoidS[T](monoidT).methods(Some(t1.s, t2.s)))
}
\end{lstlisting}
To test this code, create a value of type $T$ and perform a computation:
\begin{lstlisting}
val t = T(Right(("a", t => f => T(Left((Left(f(t)), 10))))))

scala> t |+| t
res0: T = T(Right((aa,<function1>)))
\end{lstlisting}

Another way of implementing the recursive construction is to write
the \lstinline!Monoid! typeclass using a \lstinline!trait!. Although
the code is longer, it is easier to read. The recursive instance is
implemented by
\begin{lstlisting}
def monoidT: Monoid[T] = new Monoid[T] {
  def empty: T = T(monoidS[T](monoidT).empty)   // This must be a `def empty`, not a `val empty`.
  def combine: (T, T) => T = (x, y) => T(monoidS[T](monoidT).combine(x.s, y.s))
}
\end{lstlisting}
 The recursive definition of \lstinline!monoidT! terminates because
the methods of the \lstinline!trait! are declared as \lstinline!def!
(not as \lstinline!val!). The code of \lstinline!monoidS! remains
the same; we need to rewrite \lstinline!monoidPair!, \lstinline!monoidEitherPreferB!,
and \lstinline!monoidFunc! to accommodate the new definition of the
\lstinline!Monoid! typeclass. The full code is shown in Figure~\ref{fig:Implementation-of-Monoid-typeclass-with-trait}.

The monoid laws hold for the recursive instances by induction (see
Section~\ref{subsec:The-Eq-typeclass}).

\begin{figure}
\begin{lstlisting}[frame=single,fillcolor={\color{black}},framesep={0.2mm},framexleftmargin=2mm,framexrightmargin=2mm,framextopmargin=2mm,framexbottommargin=2mm]
trait Monoid[T] {
  def empty: T
  def combine: (T, T) => T
}
implicit val monoidInt: Monoid[Int] = new Monoid[Int] {
  def empty: Int = 0
  def combine: (Int, Int) => Int = _ + _
}
implicit val monoidString: Monoid[String] = new Monoid[String] {
  def empty: String = ""
  def combine: (String, String) => String = _ + _
}
implicit class MonoidOps[T: Monoid](t: T) {
  def |+|(a: T): T = implicitly[Monoid[T]].combine(t, a)
}
def monoidPair[A: Monoid, B: Monoid]: Monoid[(A, B)] = new Monoid[(A, B)] {
  def empty: (A, B) = (implicitly[Monoid[A]].empty, implicitly[Monoid[B]].empty)
  def combine: ((A, B), (A, B)) => (A, B) = {
    case ((a1, b1), (a2, b2)) => (a1 |+| a2, b1 |+| b2)
  }
}
def monoidEitherPreferB[A: Monoid, B: Monoid] = new Monoid[Either[A, B]] {
  def empty: Either[A, B] = Left(implicitly[Monoid[A]].empty)
  def combine: (Either[A, B], Either[A, B]) => Either[A, B] = {
    case (Left(a1), Left(a2))     => Left(a1 |+| a2)
    case (Left(a), Right(b))      => Right(b) // "Take B".
    case (Right(b), Left(a))      => Right(b)
    case (Right(b1), Right(b2))   => Right(b1 |+| b2)
  }
}
def monoidFunc[A: Monoid, E] = new Monoid[E => A] {
  def empty: E => A = _ => implicitly[Monoid[A]].empty
  def combine: (E => A, E => A) => E => A = {
    case (f, g) => e => f(e) |+| g(e)
  }
}
// This type constructor will be used below to define a recursive type T.
type S[A] = Either[(Either[Int, A], Int), (String, A => (A => Int) => A)]

// If we have a Monoid instance for A, we can get a Monoid instance for S[A].
def monoidS[A](implicit ti: Monoid[A]): Monoid[S[A]] = {
  implicit val m0 = monoidEitherPreferB[Int, A]
  implicit val m1 = monoidPair[Either[Int, A], Int]
  implicit val m2 = monoidFunc[A, A => Int]
  implicit val m3 = monoidFunc[(A => Int) => A, A]
  implicit val m4 = monoidPair[String, A => (A => Int) => A]
  monoidEitherPreferB[(Either[Int, A], Int), (String, A => (A => Int) => A)]
}
// Define a recursive type T and a Monoid instance for it.
final case class T(s: S[T])
implicit def monoidT: Monoid[T] = new Monoid[T] {
  def empty: T = T(monoidS[T](monoidT).empty) // Here, `val empty` will cause a StackOverflowError.
  def combine: (T, T) => T = (x, y) => T(monoidS[T](monoidT).combine(x.s, y.s))
}
val t = T(Right(("abc", t => f => T(Left((Left(f(t)), 10))))))
val e = implicitly[Monoid[T]].empty

scala> t |+| t |+| e   // Expect to see the string "abcabc".
res0: T = T(Right((abcabc,<function1>)))
\end{lstlisting}

\caption{Implementing a recursive instance of the \lstinline!Monoid! typeclass
via a \lstinline!trait!. \label{fig:Implementation-of-Monoid-typeclass-with-trait}}
\end{figure}


\paragraph{Summary}

A \lstinline!Monoid! instance can be implemented, in at least one
way, for \emph{any} exponential-polynomial type\index{exponential-polynomial type}
expression (including recursive types) built from primitive types
and other monoids.

\begin{comment}
There exist other type constructions that work for monoids in special
cases. One example is the \textsf{``}twisted product\textsf{''} $P\times Q$ where
$P$ and $Q$ are monoids and additionally $P$ has an \textbf{action
on} $Q$. The \textsf{``}action\textsf{''} is a function $\alpha:P\rightarrow Q\rightarrow Q$
obeying the special composition law, $\alpha(p_{1})\bef\alpha(p_{2})=\alpha(p_{1}\oplus p_{2})$.
The monoidal operation is defined by
\[
(p_{1}\times q_{1})\oplus(p_{2}\times q_{2})=(p_{1}\oplus p_{2})\times(\alpha(p_{2})(q_{1})\oplus q_{2})\quad.
\]
 Examples of this construction are twisted products $\left(A\rightarrow A\right)\times A$
and $\bbnum 2\times\left(\bbnum 1+A\right)$. \textemdash{} Not sure
how useful this is, and what additional properties we need.
\end{comment}

\begin{table}
\begin{centering}
\begin{tabular}{|c|c|c|}
\hline 
\textbf{\footnotesize{}Construction} & \textbf{\footnotesize{}Type signature to implement} & \textbf{\footnotesize{}Results}\tabularnewline
\hline 
\hline 
{\footnotesize{}The }\lstinline!Unit!{\footnotesize{} type, or primitive
types} & {\footnotesize{}$\text{Monoid}^{\bbnum 1}$, $\text{Monoid}^{\text{Int}}$,
etc.} & {\footnotesize{}custom code}\tabularnewline
\hline 
{\footnotesize{}Product of monoids $A$ and $B$} & {\footnotesize{}$\text{Monoid}^{A}\times\text{Monoid}^{B}\rightarrow\text{Monoid}^{A\times B}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Co-product of monoid $A$ and semigroup $B$} & {\footnotesize{}$\text{Monoid}^{A}\times\text{Semigroup}^{B}\rightarrow\text{Monoid}^{A+B}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Function from another type $E$} & {\footnotesize{}$\text{Monoid}^{A}\rightarrow\text{Monoid}^{E\rightarrow A}$} & {\footnotesize{}$\text{Monoid}^{E\rightarrow A}$}\tabularnewline
\hline 
{\footnotesize{}Recursive type} & {\footnotesize{}$\text{Monoid}^{A}\rightarrow\text{Monoid}^{S^{A}}$
where $T\triangleq S^{T}$} & {\footnotesize{}$\text{Monoid}^{T}$}\tabularnewline
\hline 
\end{tabular}
\par\end{centering}
\caption{Type constructions producing the \lstinline!Monoid! typeclass.\label{tab:Type-constructions-for-monoid}}
\end{table}


\subsection{Pointed functors: motivation and laws\label{subsec:Pointed-functors:-motivation}}

Section~\ref{subsec:Typeclasses-for-type-constructors} showed how
to implement typeclasses for type \emph{constructors}, e.g., the \lstinline!Functor!
typeclass. Typeclass instances in such cases often contain a nested
type quantifier such as $\forall A.\left(...\right)$, so the implementation
needs to use Scala\textsf{'}s \lstinline!trait! with \lstinline!def! methods
inside. We will now look at some examples of typeclasses that add
further methods to \lstinline!Functor!. Chapter~\ref{chap:Functors,-contrafunctors,-and}
performed a structural analysis of functors, which we will extend
to the new typeclasses.

The first typeclass is a \textsf{``}pointed\textsf{''} functor. A functor type $F^{T}$
represents, in a generalized sense, \textsf{``}wrapped\textsf{''} values of type $T$.
A frequently used operation is to create a \textsf{``}wrapped\textsf{''} value of
type $F^{T}$ out of a single given value of type $T$. This operation,
usually called \lstinline!pure! in Scala libraries, is implemented
as a function with a type signature

\begin{wrapfigure}{l}{0.4\columnwidth}%
\vspace{-0.8\baselineskip}
\begin{lstlisting}
def pure[A]: A => F[A]
\end{lstlisting}
\vspace{-0.8\baselineskip}
\end{wrapfigure}%

\noindent The code notation for this function is $\text{pu}_{F}$,
and the type signature is written as $\text{pu}_{F}:\forall A.\,A\rightarrow F^{A}$. 

Some examples of pointed functors in Scala are \lstinline!Option!,
\lstinline!List!, \lstinline!Try!, and \lstinline!Future!. Each
of these type constructors has a method that \textsf{``}wraps\textsf{''} a given single
value:
\begin{lstlisting}
val x: Option[Int] = Some(10)                     // A non-empty option that holds a value.
val y: List[String] = List("abc")                 // A list that holds a single value.
val z: Try[Int] = Success(200)                    // A value computed without errors.
val f: Future[String] = Future.successful("OK")   // A `Future` value that is already available.
\end{lstlisting}
As we can see, \textsf{``}wrapping a single value\textsf{''} means a different thing
for each of the type constructors. Although the relevant methods of
these type constructors are not called \textsf{``}\lstinline!pure!\textsf{''}, we
can create a PTVF \lstinline!pure[F]! that would be defined only
for \lstinline!F! that can \textsf{``}wrap\textsf{''} a single value. Such type constructors
\lstinline!F! are called \textsf{``}\textbf{pointed}\textsf{''}. We may define the
typeclass\index{typeclass!Pointed@\texttt{Pointed}} \lstinline!Pointed!
via this code:
\begin{lstlisting}
trait Pointed[F[_]] { def pure[A]: A => F[A] }
\end{lstlisting}
Now we can implement instances of the \lstinline!Pointed! typeclass
for some functors:
\begin{lstlisting}
implicit val pointedOption = new Pointed[Option] { def pure[A]: A => Option[A] = x => Some(x)    }
implicit val pointedList   = new Pointed[List]   { def pure[A]: A => List[A]   = x => List(x)    }
implicit val pointedTry    = new Pointed[Try]    { def pure[A]: A => Try[A]    = x => Success(x) }
\end{lstlisting}
The PTVF \lstinline!pure! can be defined and used like this,

\begin{wrapfigure}{l}{0.41\columnwidth}%
\vspace{-0.95\baselineskip}
\begin{lstlisting}
def pure[F[_]: Pointed, A](x: A): F[A] =
  implicitly[Pointed[F]].pure(x)

scala> pure[Option, Int](123)
res0: Option[Int] = Some(123)
\end{lstlisting}
\vspace{-0.95\baselineskip}
\end{wrapfigure}%

\noindent When a pointed type constructor $F$ is a functor, we may
use both the functor\textsf{'}s \lstinline!map! method and the \lstinline!pure!
method. Do these two methods need to be compatible in some way? If
we \textsf{``}wrap\textsf{''} a value $123$ in a \lstinline!List! and then apply
\lstinline!.map(x => x + 1)!, we expect to obtain a list containing
$124$; any other result would break our intuition about \textsf{``}wrapping\textsf{''}.
We can generalize this situation to an arbitrary value $x^{:A}$ wrapped
using \lstinline!pure! and a function $f^{:A\rightarrow B}$ applied
to the wrapped value via \lstinline!map!:

\begin{wrapfigure}{l}{0.41\columnwidth}%
\vspace{-0.8\baselineskip}
\begin{lstlisting}[mathescape=true]
pure(x).map(f)    //   $\color{dkgreen}\text{pu}_{F}(x)\triangleright\, \scriptstyle{f^{\uparrow F}}$
\end{lstlisting}
\vspace{-0.8\baselineskip}
\end{wrapfigure}%

\noindent We expect that the result should be the same as a wrapped
$f(x)$. This expectation can be formulated as a law, called the \textbf{naturality
law}\index{naturality law!of pure@of \texttt{pure}} of \lstinline!pure!;
it must hold for any $f^{:A\rightarrow B}$:

\begin{wrapfigure}{l}{0.4\columnwidth}%
\vspace{-0.8\baselineskip}
\begin{lstlisting}
pure(x).map(f) == pure(f(x))
\end{lstlisting}
\vspace{-0.5\baselineskip}
\end{wrapfigure}%

\noindent \vspace{-0.5\baselineskip}
\[
\text{pu}_{F}(x)\triangleright f^{\uparrow F}=\text{pu}_{F}(f(x))\quad.
\]
In the $\triangleright$-notation, this law is $x\triangleright\text{pu}_{F}\triangleright f^{\uparrow F}=x\triangleright f\triangleright\text{pu}_{F}$
or equivalently $x\triangleright\text{pu}_{F}\bef f^{\uparrow F}=x\triangleright f\bef\text{pu}_{F}$.
Since both sides of the law are functions applied to an arbitrary
value $x^{:A}$, we can omit $x$ and write
\begin{equation}
\text{pu}_{F}\bef f^{\uparrow F}=f\bef\text{pu}_{F}\quad.\label{eq:naturality-law-of-pure}
\end{equation}

\noindent \begin{wrapfigure}{l}{0.28\columnwidth}%
\vspace{-4.2\baselineskip}
\[
\xymatrix{\xyScaleY{2.0pc}\xyScaleX{4.0pc}A\ar[r]\sp(0.5){\text{pu}_{F}}\ar[d]\sb(0.45){f} & F^{A}\ar[d]\sp(0.45){f^{\uparrow F}}\\
B\ar[r]\sp(0.5){\text{pu}_{F}} & F^{B}
}
\]
\vspace{-0.1\baselineskip}
\end{wrapfigure}%

\noindent \vspace{-1.9\baselineskip}

\noindent This motivates the following definition: A functor $F^{\bullet}$
is \index{pointed functor}\textbf{pointed} if there exists a fully
parametric function $\text{pu}_{F}:\forall A.\,A\rightarrow F^{A}$
satisfying the naturality law~(\ref{eq:naturality-law-of-pure})
for any function $f^{:A\rightarrow B}$.

It turns out that we can avoid checking the naturality law of pointed
functors if we use a trick: reduce \lstinline!pure! to a simpler
but equivalent form for which the law is satisfied automatically.

Both sides of the naturality law~(\ref{eq:naturality-law-of-pure})
are functions of type $A\rightarrow F^{B}$. The trick is to choose
$A=\bbnum 1$ (the \lstinline!Unit! type) and $f^{:\bbnum 1\rightarrow B}\triangleq(\_\rightarrow b)$,
a constant function returning some fixed value $b^{:B}$. Both sides
of the naturality law may then be applied to the unit value $1$ and
must evaluate to the same result:
\[
1\triangleright\text{pu}_{F}\triangleright(\_\rightarrow b)^{\uparrow F}=1\triangleright f\triangleright\text{pu}_{F}\quad.
\]
Since $1\triangleright f=f(1)=b$, we find
\begin{equation}
\text{pu}_{F}(1)\triangleright(\_\rightarrow b)^{\uparrow F}=\text{pu}_{F}(b)\quad.\label{eq:pu-via-wu}
\end{equation}
The naturality law~(\ref{eq:naturality-law-of-pure}) applies to
all types $A,B$ and to any function $f^{:A\rightarrow B}$. Thus,
Eq.~(\ref{eq:pu-via-wu}) must apply to an arbitrary value $b^{:B}$
for any type $B$. That formula expresses the function $\text{pu}_{F}$
through one value $\text{pu}_{F}(1)$ of type $F^{\bbnum 1}$. This
value can be viewed as a \textsf{``}wrapped unit\textsf{''} value. 

To perform the same derivation in Scala syntax, we may write
\begin{lstlisting}
val one: Unit = ()
val f: Unit => B = { _ => b }
pure(one).map(f) == pure(f(one)) == pure(b)    // Because f(one) == b.
\end{lstlisting}

It follows that if $\text{pu}_{F}$ satisfies the naturality law then
a single \textsf{``}wrapped unit\textsf{''} value of that function, $\text{pu}_{F}(1)$,
is sufficient to recover the entire function $\text{pu}_{F}(b)$ by
using the code
\[
\text{pu}_{F}(b)\triangleq\text{pu}_{F}(1)\triangleright(\_\rightarrow b)^{\uparrow F}\quad
\]
So, given just a \textsf{``}wrapped unit\textsf{''} value (denoted $\text{wu}_{F}$)
of type $F^{\bbnum 1}$, we can define a new function $\text{pu}_{F}$:

\begin{wrapfigure}{l}{0.46\columnwidth}%
\vspace{-0.8\baselineskip}
\begin{lstlisting}
def pure[A](x: A): F[A] = wu.map { _ => x }
\end{lstlisting}
\vspace{-0.5\baselineskip}
\end{wrapfigure}%

\noindent \vspace{-1\baselineskip}
\begin{equation}
\text{pu}_{F}^{:A\rightarrow F^{A}}\triangleq x^{:A}\rightarrow\text{wu}_{F}\triangleright(\_\rightarrow x)^{\uparrow F}\quad.\label{eq:pu-via-wu-def}
\end{equation}
Does this function satisfy the naturality law with respect to an arbitrary
$f^{:A\rightarrow B}$? It does:
\begin{align*}
{\color{greenunder}\text{expect to equal }x\triangleright f\bef\text{pu}_{F}:}\quad & x\triangleright\text{pu}_{F}\bef f^{\uparrow F}\\
{\color{greenunder}\text{definition of }\text{pu}_{F}:}\quad & =\text{wu}_{F}\triangleright(\_\rightarrow x)^{\uparrow F}\bef f^{\uparrow F}\\
{\color{greenunder}\text{functor composition law of }F:}\quad & =\text{wu}_{F}\triangleright(\left(\_\rightarrow x\right)\bef f)^{\uparrow F}\\
{\color{greenunder}\text{compute function composition}:}\quad & =\text{wu}_{F}\triangleright(\_\rightarrow f(x))^{\uparrow F}\\
{\color{greenunder}\text{definition of }\text{pu}_{F}:}\quad & =\text{pu}_{F}(f(x))\\
{\color{greenunder}\triangleright\text{-notation}:}\quad & =x\triangleright f\triangleright\text{pu}_{F}=x\triangleright f\bef\text{pu}_{F}\quad.
\end{align*}
Applied to the unit value, this new function gives $\text{pu}_{F}(1)=\text{wu}_{F}$
because
\begin{align*}
{\color{greenunder}\triangleright\text{-notation}:}\quad & \text{pu}_{F}(1)=1\triangleright\text{pu}_{F}\\
{\color{greenunder}\text{definition of }\text{pu}_{F}\text{ via }\text{wu}_{F}:}\quad & =\text{wu}_{F}\triangleright(\_\rightarrow1)^{\uparrow F}\\
{\color{greenunder}\text{the function }(\_\rightarrow1)\text{ is the identity function }\text{id}^{:\bbnum 1\rightarrow\bbnum 1}:}\quad & =\text{wu}_{F}\triangleright\text{id}^{\uparrow F}\\
{\color{greenunder}\text{functor identity law of }F:}\quad & =\text{wu}_{F}\triangleright\text{id}=\text{wu}_{F}\quad.
\end{align*}

To summarize our results: for any functor $F$,
\begin{itemize}
\item If $F$ is a lawful pointed functor, its \lstinline!pure! method
satisfies Eq.~(\ref{eq:pu-via-wu-def}) where $\text{wu}_{F}\triangleq\text{pu}_{F}(1)$
is a fixed \textsf{``}wrapped unit\textsf{''} value of type $F^{\bbnum 1}$.
\item If any \textsf{``}wrapped unit\textsf{''} value $\text{wu}_{F}:F^{\bbnum 1}$ is given,
we may define a \lstinline!pure! method by Eq.~(\ref{eq:pu-via-wu-def})
and make the functor $F$ into a lawful pointed functor; the naturality
law will be satisfied automatically. The value $\text{pu}_{F}(1)$
will be equal to the originally given value $\text{wu}_{F}$.
\end{itemize}
So, the types of $\text{pu}_{F}$ and $\text{wu}_{F}$ are\textbf{
equivalent}\index{type equivalence}: each one can be converted into
the other and back without loss of information. We may define a pointed
functor equivalently as a functor with a chosen value $\text{wu}_{F}$
of type $F^{\bbnum 1}$. When reasoning about pointed functors, it
is simpler to use the definition via the \textsf{``}wrapped unit\textsf{''} $\text{wu}_{F}$
because it has a simpler type and no laws. When writing code, the
\lstinline!pure! method is more convenient.

\subsection{Pointed functors: structural analysis\label{subsec:Pointed-functors:-structural-analysis}}

To perform structural analysis, we begin with the known functor-building
constructions from Chapter~\ref{chap:Functors,-contrafunctors,-and}
and impose an additional requirement that a \textsf{``}wrapped unit\textsf{''} value
$\text{wu}_{F}:F^{\bbnum 1}$ should exist. As we have seen in the
previous section, no additional laws need to be checked. The results
are shown in Table~\ref{tab:Type-constructions-for-pointed-functor}.
The typeclass can be defined by the simpler code,
\begin{lstlisting}
final case class Pointed[F[_]](wu: F[Unit])
def pure[F[_]: Pointed : Functor, A](a: A): F[A] = implicitly[Pointed[F]].wu.map(_ => a)
\end{lstlisting}

When the type $F^{\bbnum 1}$ has several distinct values, the choice
of $\text{wu}_{F}$ is application-dependent. E.g., if $F^{A}\triangleq\text{List}^{A}$,
the type $\text{List}^{\bbnum 1}$ has values such as an empty list
\lstinline!List[Unit]()!, the list of length $1$, i.e., \lstinline!List(())!,
the list of length $2$, i.e., \lstinline!List((), ())!, etc. Each
of these choices gives a valid \lstinline!Pointed! instance for the
\lstinline!List! functor. It is up to the programmer to choose the
\lstinline!Pointed! instance that will be useful for the application
at hand. In the case of \lstinline!List!, the standard choice \lstinline!wu == List(())!
and correspondingly \lstinline!pure(x) = List(x)! is motivated by
the usage of the \lstinline!List! type constructor to represent several
possibilities, e.g., in a search problem; then the \textsf{``}pure\textsf{''} list
represents the situation with only one possibility.

\paragraph{Nameless type-to-type functions}

To implement the \lstinline!Pointed! typeclass instances for the
following constructions, we need to use some advanced syntax features
of Scala. In the previous sections, we wrote PTVFs parameterized by
a type built out of other types, for example
\begin{lstlisting}
def monoidPair[A: Monoid, B: Monoid]: Monoid[(A, B)] = ???
\end{lstlisting}
The function \lstinline!monoidPair! creates a typeclass instance
for the type $A\times B$, which is built out of the types $A$ and
$B$. In Scala, the typeclass instance is a value of type \lstinline!Monoid[(A, B)]!.
The analog for type constructors is a value of type \lstinline!Pointed[L]!
where the type constructor \lstinline!L! is defined by the type alias
\begin{lstlisting}
type L[A] = (F[A], G[A])
\end{lstlisting}
However, the following declaration of the analogous function \lstinline!pointedPair!
is invalid in Scala:
\begin{lstlisting}
def pointedPair[F[_]: Pointed, G[_]: Pointed]: Pointed[L]     // Does not work in Scala.
\end{lstlisting}
It is not possible to use the type alias \lstinline!L! within this
function declaration, because the type alias needs to use the type
parameters \lstinline!F! and \lstinline!G! that are defined only
within the type signature of the function. To achieve that, we would
need somehow to insert a new type alias declaration within the type
signature of \lstinline!pointedPair!, but the syntax of Scala does
not support that:
\begin{lstlisting}
def pointedPair[F[_]: Pointed, G[_]: Pointed]: {            // Not a valid Scala syntax.
    type L[A] = (F[A], G[A]) // Temporarily define a type constructor L, and now use it:
    Pointed[L] }
\end{lstlisting}
The return type is required to be \lstinline!Pointed[L]!, where \lstinline!L!
needs to be a type expression that defines a type constructor, i.e.,
a type-to-type function with a \emph{single} type parameter. Writing
a type alias with parameters \lstinline!F! and \lstinline!G!,
\begin{lstlisting}
type L[F[_], G[_], A] = (F[A], G[A])
def pointedPair[F[_]: Pointed, G[_]: Pointed]: Pointed[L[F, G]]    // Still incorrect.
\end{lstlisting}
will not help because the type expression \lstinline!L[F, G]! in
\lstinline!Pointed[L[F, G]]! is not a valid type constructor with
one type parameter. We cannot define a new type name (such as \lstinline!L!)
within the type signature; what we need is a \emph{nameless} type-to-type
function (i.e., a nameless type constructor).

The special Scala plugin called the \index{kind@\textsf{``}kind projector\textsf{''} plugin}\textsf{``}kind
projector\textsf{''}\footnote{\texttt{\href{https://github.com/typelevel/kind-projector}{https://github.com/typelevel/kind-projector}}}
adds syntax for nameless type constructors. The syntax is similar
to defining a nameless function: for instance, the pair functor $F^{\bullet}\times G^{\bullet}$
is defined as \lstinline!Lambda[X => (F[X], G[X])]!. Such type expressions
can be understood as nameless\index{nameless type-to-type function}
type-to-type functions. When using the \textsf{``}kind projector\textsf{''} plugin,
the syntax for defining \lstinline!pointedPair! is
\begin{lstlisting}
def pointedPair[F[_]: Pointed, G[_]: Pointed]: Pointed[Lambda[X => (F[X], G[X])]] = ???
\end{lstlisting}
Scala 3 will support a shorter syntax for nameless type-to-type functions,
e.g., \lstinline![X] => (F[X], G[X])!. We will use the \textsf{``}kind projector\textsf{''}
syntax in this book\textsf{'}s code examples.

\paragraph{Fixed types}

A constant functor $\text{Const}^{Z,\bullet}$ is defined as $\text{Const}^{Z,A}\triangleq Z$,
where $Z$ is a fixed type. A \textsf{``}wrapped unit\textsf{''} value is thus also
a value of type $Z$. Since we cannot produce values of an arbitrary
type $Z$ from scratch, the constant functor is not pointed in general.
The constant functor \emph{will} be pointed when there exists a known
value of type $Z$. Examples are $Z=\bbnum 1$ or $Z=\bbnum 1+U$
(where $U$ is an arbitrary type). If we know that $Z$ is equivalent
to $\bbnum 1+U$, we will be able to produce a value of type $Z$
as $1+\bbnum 0^{:U}$. In that case, we set $\text{wu}_{\text{Const}^{Z,\bullet}}=1+\bbnum 0^{:U}$.
\begin{lstlisting}
type Const[Z, A] = Z
def pointedOpt[U]: Pointed[Lambda[X => Const[Option[U], X]]] = Pointed(None: Const[Option[U], Unit])
\end{lstlisting}
Other cases are types such as $Z=\text{Int}$, $Z=\text{String}$,
etc., that have well-known \textsf{``}default\textsf{''} values.

\paragraph{Type parameters}

The identity functor $\text{Id}^{A}\triangleq A$ is pointed since
$\text{Id}^{\bbnum 1}=\bbnum 1$, and we can set $\text{wu}_{\text{Id}}=1$.
\begin{lstlisting}
type Id[A] = A
def pointedId: Pointed[Id] = Pointed[Id](())
\end{lstlisting}

The other functor constructions that work by setting type parameters
are functor compositions. If $F$ and $G$ are two functors or two
contrafunctors then $F\circ G$ is a functor. The functor $F\circ G$
is pointed when we can create a value of type $F^{G^{\bbnum 1}}$.
If both $F$ and $G$ are pointed, we can apply $F$\textsf{'}s \lstinline!pure!
method to $\text{wu}_{G}:G^{\bbnum 1}$ and obtain a value of type
$F^{G^{\bbnum 1}}$.
\begin{lstlisting}
def pointedFoG[F[_]: Pointed : Functor, G[_]: Pointed]: Pointed[Lambda[X => F[G[X]]]]
  = Pointed[Lambda[X => F[G[X]]]](pure[F, G[Unit]](implicitly[Pointed[G]].wu))     
\end{lstlisting}
The case when $F$ and $G$ are contrafunctors requires us to assume
that $F$ belongs to the \textsf{``}pointed contrafunctor\textsf{''} typeclass (see
Section~\ref{subsec:Pointed-contrafunctors} below). A pointed contrafunctor
has a \textsf{``}wrapped unit\textsf{''} value of type $F^{\bbnum 1}$, which can
be transformed into $F^{A}$ for any type $A$ by using \lstinline!contramap!
with a constant function $A\rightarrow\bbnum 1$:
\begin{lstlisting}
def cpure[F[_]: Pointed : Contrafunctor, A]: F[A] = implicitly[Pointed[F]].wu.cmap(_ => ())
\end{lstlisting}
In this way, we can create a value of type $F^{G^{\bbnum 1}}$. The
contrafunctor $G$ does not need to be pointed.
\begin{lstlisting}
def pointedCFoG[F[_]: Pointed : Contrafunctor, G[_]]: Pointed[Lambda[X => F[G[X]]]] =
  Pointed[Lambda[X => F[G[X]]]](cpure[F, G[Unit]])
\end{lstlisting}


\paragraph{Products}

If $F$ and $G$ are two pointed functors, is the functor product
$L^{A}\triangleq F^{A}\times G^{A}$ a pointed functor? We need to
produce a value $\text{wu}_{L}:F^{\bbnum 1}\times G^{\bbnum 1}$,
and we have values $\text{wu}_{F}:F^{\bbnum 1}$ and $\text{wu}_{G}:G^{\bbnum 1}$.
It is clear that we must set $\text{wu}_{L}=\text{wu}_{F}\times\text{wu}_{G}$.
\begin{lstlisting}
def pointedFxG[F[_]: Pointed, G[_]: Pointed]: Pointed[Lambda[X => (F[X],G[X])]] =
  Pointed[Lambda[X => (F[X],G[X])]]((implicitly[Pointed[F]].wu, implicitly[Pointed[G]].wu))
\end{lstlisting}


\paragraph{Co-products}

If $F$ and $G$ are two pointed functors, is the functor co-product
$L^{A}\triangleq F^{A}+G^{A}$ a pointed functor? We need to produce
a value $\text{wu}_{L}:F^{\bbnum 1}+G^{\bbnum 1}$, and we have values
$\text{wu}_{F}:F^{\bbnum 1}$ and $\text{wu}_{G}:G^{\bbnum 1}$. There
are two choices, $\text{wu}_{L}=\text{wu}_{F}+\bbnum 0^{:G^{\bbnum 1}}$
and $\text{wu}_{L}=\bbnum 0^{:F^{\bbnum 1}}+\text{wu}_{G}$, both
making $L^{\bullet}$ a pointed functor. 

It is sufficient if just $F^{\bullet}$ is a pointed functor: $\text{wu}_{L}\triangleq\text{wu}_{F}+\bbnum 0^{:G^{\bbnum 1}}$
is a \lstinline!Pointed! typeclass instance for $F^{\bullet}+G^{\bullet}$,
even if $G^{\bullet}$ is not pointed.
\begin{lstlisting}
def pointedEitherFG[F[_]: Pointed, G[_]]: Pointed[Lambda[X => Either[F[X],G[X]]]] =
  Pointed[Lambda[X => Either[F[X],G[X]]]](Left(implicitly[Pointed[F]].wu))
\end{lstlisting}


\paragraph{Functions}

If $C$ is any contrafunctor and $F$ is a pointed functor, the exponential
functor $L^{A}\triangleq C^{A}\rightarrow F^{A}$ will be pointed
if we are able to produce a value $\text{wu}_{L}:C^{\bbnum 1}\rightarrow F^{\bbnum 1}$.
We already have a value $\text{wu}_{F}:F^{\bbnum 1}$, and we cannot
use a value of type $C^{\bbnum 1}$ with a general contrafunctor $C$.
So, we have to set $\text{wu}_{L}\triangleq(\_\rightarrow\text{wu}_{F})$.
This makes $L$ into a pointed functor.
\begin{lstlisting}
def pointedFuncFG[F[_]: Pointed, C[_]]: Pointed[Lambda[X => C[X] => F[X]]] =
  Pointed[Lambda[X => C[X] => F[X]]](_ => implicitly[Pointed[F]].wu)
\end{lstlisting}


\paragraph{Recursive types}

The recursive construction for functors (see Statement~\ref{subsec:functor-Statement-functor-recursive})
assumes a bifunctor $S^{\bullet,\bullet}$ and defines a recursive
functor $F^{\bullet}$ via the type equation $F^{A}\triangleq S^{A,F^{A}}$.
The functor $F^{\bullet}$ will be pointed if we can compute a value
$\text{wu}_{F}$ of type $F^{\bbnum 1}$. The type $F^{\bbnum 1}$
is a recursive type defined via the type equation $F^{\bbnum 1}\triangleq S^{\bbnum 1,F^{\bbnum 1}}$.
If that type is not void, i.e., if there exists some value of that
type, we will be able to define $\text{wu}_{F}$ as that value. 

How can we construct $\text{wu}_{F}$ for a given bifunctor $S$?
The procedure can be derived by structural analysis of $S$ (see Section~\ref{subsec:Recursive-types-and-the-existence-of-their-values}
below). For \emph{polynomial} bifunctors $S$ (which is the most often
used kind of bifunctors), the necessary and sufficient condition is
that the type $S^{\bbnum 1,\bbnum 0}$ should be non-void. If we can
create a value of type $S^{\bbnum 1,\bbnum 0}$ , arguments shown
in Section~\ref{subsec:Recursive-types-and-the-existence-of-their-values}
will guarantee that we can also create a value of type $F^{\bbnum 1}$,
and so the recursive functor $F$ will be pointed.

As an example, consider the polynomial bifunctor $S^{A,R}\triangleq A+A\times R$.
The corresponding recursive functor $F^{A}\triangleq S^{A,F^{A}}=A+A\times F^{A}$
is the non-empty list (see Example~\ref{subsec:Disjunctive-Example-non-empty-list-foldLeft},
Table~\ref{tab:Examples-of-recursive-disjunctive-type-equations},
and Statement~\ref{subsec:functor-Statement-functor-recursive}).
The type $F^{A}$ can be (non-rigorously) viewed as an \textsf{``}infinite
disjunction\textsf{''}
\[
F^{A}=A+A\times(A+A\times\left(A+...\right))=A+A\times A+A\times A\times A+...
\]
Since the type $S^{\bbnum 1,\bbnum 0}=\bbnum 1+\bbnum 1\times\bbnum 0\cong\bbnum 1$
is non-void, the necessary and sufficient condition holds, so we expect
that the recursive construction will work. The type $F^{\bbnum 1}$
is defined by 
\[
F^{\bbnum 1}\triangleq S^{\bbnum 1,F^{\bbnum 1}}=\bbnum 1+\bbnum 1\times F^{\bbnum 1}\cong\bbnum 1+F^{\bbnum 1}\quad.
\]
This type can be (non-rigorously) viewed as an \textsf{``}infinite disjunction\textsf{''}
\[
F^{\bbnum 1}\cong\bbnum 1+F^{\bbnum 1}\cong\bbnum 1+\bbnum 1+F^{\bbnum 1}=\bbnum 1+\bbnum 1+\bbnum 1+...
\]
It is clear that a value of that type can be computed, for example,
as 
\[
\text{wu}_{F}=1+\bbnum 0+\bbnum 0+...\cong1+\bbnum 0^{:F^{\bbnum 1}}\quad.
\]
In Scala, this is \lstinline!Left(())!. So, a \lstinline!Pointed!
typeclass instance for $F$ is implemented by the following code:

\begin{wrapfigure}{l}{0.42\columnwidth}%
\vspace{-0.8\baselineskip}
\begin{lstlisting}
type S[A, R] = Either[A, (A, R)]
final case class F[A](s: S[A, F[A]])
implicit val pointedF: Pointed[F] =
  Pointed( F(Left(())) )
\end{lstlisting}
\vspace{-0.5\baselineskip}
\end{wrapfigure}%

The corresponding \lstinline!pure! method will use $F$\textsf{'}s \lstinline!map!
to transform $\text{wu}_{F}=1+\bbnum 0+\bbnum 0+...$ into 
\[
a+\bbnum 0+\bbnum 0+...:A+A\times A+A\times A\times A+...\quad.
\]
The \lstinline!pure! method of $F$ creates a non-empty list with
a single element $a^{:A}$.

\paragraph{Summary}

Can we recognize a pointed functor $F$ by looking at its type expression,
e.g.
\[
F^{A,B}\triangleq\left((\bbnum 1+A\rightarrow\text{Int})\rightarrow A\times B\right)+\text{String}\times A\times A\quad?
\]
This type constructor is a functor in both $A$ and $B$, and we ask
whether $F$ is pointed with respect to $A$ and/or with respect to
$B$.

To answer this question with respect to $A$, we set $A=\bbnum 1$
in $F^{A,B}$ and obtain the type expression
\[
F^{\bbnum 1,B}=\left((\bbnum 1+\bbnum 1\rightarrow\text{Int})\rightarrow\bbnum 1\times B\right)+\text{String}\times\bbnum 1\times\bbnum 1\cong\left(\left(\bbnum 2\rightarrow\text{Int}\right)\rightarrow B\right)+\text{String}\quad.
\]
The functor $F$ will be pointed with respect to $A$ if we can compute
a value of this type from scratch. At the outer level, this type expression
is a disjunctive type with two parts; it is sufficient to compute
one of the parts. Can we compute a value of type $\left(\bbnum 2\rightarrow\text{Int}\right)\rightarrow B$?
Since the parameter $B$ is an arbitrary, unknown type, we cannot
construct values of type $B$ using a given value of type $\bbnum 2\rightarrow\text{Int}$.
The remaining possibility is to compute the second part of the co-product,
which is $\text{String}\times\bbnum 1\times\bbnum 1$. We are able
to compute a value of this type because \lstinline!String! is a fixed
type with a known default value (an empty string). So, we conclude
that $F^{A,B}$ is pointed with respect to $A$.

Considering now the type parameter $B$, we set $B=\bbnum 1$ and
obtain
\[
F^{A,\bbnum 1}=\left((\bbnum 1+A\rightarrow\text{Int})\rightarrow A\times\bbnum 1\right)+\text{String}\times A\times A\quad.
\]
The type $A$ is now an arbitrary and unknown type, so we cannot compute
any values of $A$ or $\text{String}\times A\times A$ from scratch.
The function type $(\bbnum 1+A\rightarrow\text{Int})\rightarrow A\times\bbnum 1$
cannot be implemented because a value of type $A$ cannot be computed
from a function $\bbnum 1+A\rightarrow\text{Int}$ that \emph{consumes}
values of type $A$. So, $F^{A,B}$ is not pointed with respect to
$B$.

\begin{table}
\begin{centering}
\begin{tabular}{|c|c|c|}
\hline 
\textbf{\footnotesize{}Construction} & \textbf{\footnotesize{}Type signature to implement} & \textbf{\footnotesize{}Results}\tabularnewline
\hline 
\hline 
{\footnotesize{}Constant functor returning a fixed type $Z$} & {\footnotesize{}value of type $Z$} & {\footnotesize{}$Z$ has a default}\tabularnewline
\hline 
{\footnotesize{}Identity functor} & {\footnotesize{}$\bbnum 1$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Composition of pointed functors/contrafunctors} & {\footnotesize{}$\text{Pointed}^{F^{\bullet}}\times\text{Pointed}^{G^{\bullet}}\rightarrow\text{Pointed}^{F^{G^{\bullet}}}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Product of pointed functors $F$ and $G$} & {\footnotesize{}$\text{Pointed}^{F^{\bullet}}\times\text{Pointed}^{G^{\bullet}}\rightarrow\text{Pointed}^{F^{\bullet}\times G^{\bullet}}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Co-product of a pointed functor $F$ and any $G$} & {\footnotesize{}$\text{Pointed}^{F^{\bullet}}\times\text{Functor}^{G^{\bullet}}\rightarrow\text{Pointed}^{F^{\bullet}+G^{\bullet}}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Function from any $C$ to a pointed $F$} & {\footnotesize{}$\text{Pointed}^{F^{\bullet}}\times\text{Contrafunctor}^{C^{\bullet}}\rightarrow\text{Pointed}^{C^{\bullet}\rightarrow F^{\bullet}}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Recursive type} & {\footnotesize{}$\text{Pointed}^{F^{\bullet}}\rightarrow\text{Pointed}^{S^{\bullet,F^{\bullet}}}$
where $F^{A}\triangleq S^{A,F^{A}}$} & {\footnotesize{}$\text{Pointed}^{F^{\bullet}}$}\tabularnewline
\hline 
\end{tabular}
\par\end{centering}
\caption{Type constructions producing the \lstinline!Pointed! functor typeclass.\label{tab:Type-constructions-for-pointed-functor}}
\end{table}


\subsection{Co-pointed functors\label{subsec:Co-pointed-functors}}

Pointed functors provide the functionality of wrapping a given value
in a \textsf{``}pure wrapper\textsf{''}. Another useful operation is \emph{extracting}
a value from a given \textsf{``}wrapper\textsf{''}:

\begin{wrapfigure}{l}{0.5\columnwidth}%
\vspace{-0.8\baselineskip}
\begin{lstlisting}
def extract[F[_], A]: F[A] => A
\end{lstlisting}
\vspace{-0.5\baselineskip}
\end{wrapfigure}%

\noindent \vspace{-0.5\baselineskip}
\[
\text{ex}:\forall A.\,F^{A}\rightarrow A\quad.
\]

Functors having this operation are called \index{co-pointed functor}\textbf{co-pointed}.
We may define the \lstinline!Copointed! typeclass\index{typeclass!Copointed@\texttt{Copointed}}
as
\begin{lstlisting}
trait Copointed[F[_]] { def ex[A]: F[A] => A }
def extract[F[_]: Copointed, A](f: F[A]): A = implicitly[Copointed[F]].ex(f)
\end{lstlisting}
The \lstinline!extract! function must be fully parametric and obey
the \index{naturality law!of extract@of \texttt{extract}}\textbf{naturality
law} (compare to Eq.~(\ref{eq:naturality-law-of-pure})),
\begin{equation}
\text{ex}_{F}\bef f=f^{\uparrow F}\bef\text{ex}_{F}\quad.\label{eq:naturality-law-of-extract}
\end{equation}

\begin{wrapfigure}{l}{0.25\columnwidth}%
\vspace{-4.6\baselineskip}
\[
\xymatrix{\xyScaleY{2.0pc}\xyScaleX{4.0pc}F^{A}\ar[r]\sp(0.5){\text{ex}_{F}}\ar[d]\sb(0.45){f^{\uparrow F}} & A\ar[d]\sp(0.45){~f}\\
F^{B}\ar[r]\sp(0.5){\text{ex}_{F}} & B
}
\]

\vspace{-1.5\baselineskip}
\end{wrapfigure}%

\noindent The naturality law formulates our expectation that the extractor
function somehow \textsf{``}selects\textsf{''} a value of type $A$ among all the
values wrapped by $F^{A}$, and the \textsf{``}selection\textsf{''} works independently
of the values. If all wrapped values are transformed by a function
$f$ into wrapped values of type $B$, the extractor function will
still select a value of type $B$ in the same way as it did for values
of type $A$. So, the result will be the same as if we first extracted
a value of type $A$ and then transformed that value with $f$.

Both sides of the law~(\ref{eq:naturality-law-of-extract}) are functions
of type $F^{A}\rightarrow B$. We saw in the previous section that,
when $F$ is a functor, the type of the \lstinline!pure! method of
the \lstinline!Pointed! typeclass is equivalent to the type $F^{\bbnum 1}$.
That provides a simpler form of the \lstinline!Pointed! typeclass.
For co-pointed functors, there is no simpler form of the \lstinline!extract!
method. If we set $A=\bbnum 1$ and $f^{:\bbnum 1\rightarrow B}\triangleq(1\rightarrow b)$
in the naturality law, both sides will become functions of type $F^{\bbnum 1}\rightarrow B$.
But the type $F^{\bbnum 1}$ might be void, or a value of type $F^{\bbnum 1}$
may not be computable via fully parametric code. So, we cannot deduce
any further information from the naturality law of co-pointed functors. 

However, if $F$ is a pointed functor, we \emph{will} have a chosen
value $\text{wu}_{F}:F^{\bbnum 1}$ to which we may then apply both
sides of the naturality law~(\ref{eq:naturality-law-of-extract})
and obtain\footnote{The symbol $\overset{!}{=}$ means \textsf{``}must be equal, according to
what we know\textsf{''}.}
\[
\text{wu}_{F}\triangleright\text{ex}_{F}\bef f\overset{!}{=}\text{wu}_{F}\triangleright f^{\uparrow F}\bef\text{ex}_{F}\quad.
\]
Calculating both sides separately, we find
\begin{align*}
 & \text{wu}_{F}\triangleright\text{ex}_{F}\bef f=\text{wu}_{F}\triangleright\text{ex}_{F}\triangleright f=1\triangleright f=b\quad.\\
 & \text{wu}_{F}\triangleright f^{\uparrow F}\bef\text{ex}_{F}=b\triangleright\text{pu}_{F}\bef\text{ex}_{F}\quad.
\end{align*}
So, we know that $b\triangleright\text{pu}_{F}\bef\text{ex}_{F}\overset{!}{=}b$.
This can hold for all $b^{:B}$ only if 
\[
\text{pu}_{F}\bef\text{ex}_{F}=\text{id}\quad.
\]
This additional \textbf{compatibility} \textbf{law}\index{compatibility law!for pointed and co-pointed functors}
is a consequence of naturality laws if the functor $F$ is pointed
and co-pointed at the same time.

Let us perform structural analysis for co-pointed functors; the results
are shown in Table~\ref{tab:Type-constructions-for-copointed-functor}.

\paragraph{Fixed types}

A constant functor $\text{Const}^{Z,A}\triangleq Z$ is \emph{not}
co-pointed because we cannot implement $\forall A.\,Z\rightarrow A$
(a value of an arbitrary type $A$ cannot be computed from a value
of a fixed type $Z$).

\paragraph{Type parameters}

The identity functor $\text{Id}^{A}\triangleq A$ is co-pointed with
$\text{ex}\triangleq\text{id}^{:A\rightarrow A}$. An identity function
will always satisfy any naturality law.
\begin{lstlisting}
type Id[A] = A
def copointedId: Copointed[Id] = new Copointed[Id] { def ex[A]: Id[A] => A = identity }
\end{lstlisting}

Composition of two co-pointed functors $F$, $G$ is co-pointed:
\[
\text{ex}_{F\circ G}\triangleq h^{:F^{G^{A}}}\rightarrow\text{ex}_{G}(\text{ex}_{F}(h))\quad\text{ or equivalently }\quad\text{ex}_{F\circ G}=\text{ex}_{F}\bef\text{ex}_{G}\quad.
\]
\begin{lstlisting}
def copointedFoG[F[_]: Copointed, G[_]: Copointed]: Copointed[Lambda[X => F[G[X]]]] =     
  new Copointed[Lambda[X => F[G[X]]]] {
    def ex[A]: F[G[A]] => A = extract[F,G[A]] _ andThen extract[G, A]
  }
\end{lstlisting}
The naturality law holds for $\text{ex}_{F\circ G}$ because
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{ex}_{F\circ G}\bef f:}\quad & \gunderline{f^{\uparrow F\circ G}}\bef\gunderline{\text{ex}_{F\circ G}}\\
{\color{greenunder}\text{definition of }\ensuremath{f^{\uparrow F\circ G}},\text{ see Eq.~(\ref{eq:def-functor-composition-fmap})}:}\quad & =\gunderline{(f^{\uparrow G})^{\uparrow F}\bef\text{ex}_{F}}\bef\text{ex}_{G}\\
{\color{greenunder}\text{naturality law of }\text{ex}_{F}:}\quad & =\text{ex}_{F}\bef\gunderline{f^{\uparrow G}\bef\text{ex}_{G}}\\
{\color{greenunder}\text{naturality law of }\text{ex}_{G}:}\quad & =\gunderline{\text{ex}_{F}\bef\text{ex}_{G}}\bef f=\text{ex}_{F\circ G}\bef f\quad.
\end{align*}


\paragraph{Products}

If functors $F$ and $G$ are co-pointed, we can implement a function
of type $F^{A}\times G^{A}\rightarrow A$ in two different ways: by
discarding $F^{A}$ or by discarding $G^{A}$. With either choice,
the functor product $F^{\bullet}\times G^{\bullet}$ is made into
a co-pointed functor. For instance, if we choose to discard $G^{A}$
then the functor $G$ will not need to be co-pointed, and the code
for the \lstinline!extract! method will be 
\[
\text{ex}_{F\times G}\triangleq f^{:F^{A}}\times g^{:G^{A}}\rightarrow\text{ex}_{F}(f)=\pi_{1}\bef\text{ex}_{F}\quad,
\]
where we used the pair projection function $\pi_{1}\triangleq(a\times b\rightarrow a)$.
\begin{lstlisting}
def copointedFxG[F[_]: Copointed, G[_]]: Copointed[Lambda[X => (F[X],G[X])]] =
  new Copointed[Lambda[X => (F[X], G[X])]] {
    def ex[A]: ((F[A], G[A])) => A = { case (f, g) => extract(f) }
  }
\end{lstlisting}
The following calculation verifies the naturality law~(\ref{eq:naturality-law-of-extract})
for this definition of $\text{ex}_{F\times G}$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{ex}_{F\times G}\bef f:}\quad & \gunderline{f^{\uparrow F\times G}}\bef\text{ex}_{F\times G}\\
{\color{greenunder}\text{definition of }f^{\uparrow F\times G},\text{ see Eq.~(\ref{eq:def-of-functor-product-fmap})}:}\quad & =(f^{\uparrow F}\boxtimes f^{\uparrow G})\bef\gunderline{\text{ex}_{F\times G}}\\
{\color{greenunder}\text{definition of }\text{ex}_{F\times G}:}\quad & =\gunderline{(f^{\uparrow F}\boxtimes f^{\uparrow G})\bef\pi_{1}}\bef\text{ex}_{F}\\
{\color{greenunder}\text{use the property }(p\boxtimes q)\bef\pi_{1}=\pi_{1}\bef p:}\quad & =\pi_{1}\bef\gunderline{f^{\uparrow F}\bef\text{ex}_{F}}\\
{\color{greenunder}\text{naturality law of }\text{ex}_{F}:}\quad & =\gunderline{\pi_{1}\bef\text{ex}_{F}}\bef f\\
{\color{greenunder}\text{definition of }\text{ex}_{F\times G}:}\quad & =\text{ex}_{F\times G}\bef f\quad.
\end{align*}
To demonstrate the property $(p\boxtimes q)\bef\pi_{1}=\pi_{1}\bef p$
used in this proof, apply both sides to $a\times b$:
\begin{align*}
 & (a\times b)\triangleright(p\boxtimes q)\,\gunderline{\bef}\,\pi_{1}=\gunderline{(a\times b)\triangleright(p\boxtimes q)}\triangleright\pi_{1}=(p(a)\times q(b))\triangleright\pi_{1}=p(a)\quad,\\
 & (a\times b)\triangleright\pi_{1}\,\gunderline{\bef}\,p=\gunderline{(a\times b)\triangleright\pi_{1}}\triangleright p=a\triangleright p=p(a)\quad.
\end{align*}


\paragraph{Co-products}

For co-pointed functors $F$ and $G$, there is only one possible
implementation of the type signature $\text{ex}_{F+G}:F^{A}+G^{A}\rightarrow A$,
given that we have functions $\text{ex}_{F}$ and $\text{ex}_{G}$:

\begin{wrapfigure}{l}{0.62\columnwidth}%
\vspace{-0.85\baselineskip}
\begin{lstlisting}
def copointedEitherFG[F[_]: Copointed, G[_]: Copointed]:
                 Copointed[Lambda[X => Either[F[X],G[X]]]] =
  new Copointed[Lambda[X => Either[F[X],G[X]]]] {
    def ex[A]: Either[F[A], G[A]] => A = {
      case Left(f)    => extract(f)
      case Right(g)   => extract(g)
    }
  }
\end{lstlisting}
\vspace{-2.5\baselineskip}
\end{wrapfigure}%

\noindent \vspace{-0.15\baselineskip}
\[
\text{ex}_{F+G}\triangleq\,\begin{array}{|c||c|}
 & A\\
\hline F^{A} & \text{ex}_{F}\\
G^{A} & \text{ex}_{G}
\end{array}\quad.
\]

To verify that $\text{ex}_{F+G}$ satisfies the naturality law, we
compute: 

\begin{align*}
{\color{greenunder}\text{expect to equal }\text{ex}_{F+G}\bef f:}\quad & \gunderline{f^{\uparrow F+G}}\bef\gunderline{\text{ex}_{F+G}}\\
{\color{greenunder}\text{definition of }f^{\uparrow F+G},\text{ see Eq.~(\ref{eq:f-coproduct-functor-def-fmap})}:}\quad & =\,\begin{array}{||cc|}
f^{\uparrow F} & \bbnum 0\\
\bbnum 0 & f^{\uparrow G}
\end{array}\,\bef\,\begin{array}{||c|}
\text{ex}_{F}\\
\text{ex}_{G}
\end{array}\\
{\color{greenunder}\text{matrix function composition}:}\quad & =\,\,\begin{array}{||c|}
\gunderline{f^{\uparrow F}\bef\text{ex}_{F}}\\
\gunderline{f^{\uparrow G}\bef\text{ex}_{G}}
\end{array}\\
{\color{greenunder}\text{naturality laws of }\text{ex}_{F}\text{ and }\text{ex}_{G}:}\quad & =\,\begin{array}{||c|}
\text{ex}_{F}\,\gunderline{\bef f}\\
\text{ex}_{G}\,\gunderline{\bef f}
\end{array}\,=\,\gunderline{\begin{array}{||c|}
\text{ex}_{F}\\
\text{ex}_{G}
\end{array}}\,\bef f=\text{ex}_{F+G}\bef f\quad.
\end{align*}


\paragraph{Functions}

An exponential functor of the form $L^{A}\triangleq C^{A}\rightarrow P^{A}$
(where $C$ is a contrafunctor and $P$ is a functor) will be co-pointed
if we can implement a function of type $\forall A.\,(C^{A}\rightarrow P^{A})\rightarrow A$,
\[
\text{ex}_{L}\triangleq h^{:C^{A}\rightarrow P^{A}}\rightarrow\text{???}^{:A}\quad.
\]
Since the type $A$ is arbitrary, the only way of computing a value
of type $A$ is somehow to use the function $h$. The only way of
using $h$ is to apply it to a value of type $C^{A}$, which will
yield a value of type $P^{A}$. So, we need to assume that we can
somehow create a value of type $C^{A}$, for any type $A$. We may
call a contrafunctor $C$ with a method \lstinline!cpure! of type
$\forall A.\,C^{A}$ a \textbf{pointed contrafunctor}\index{pointed contrafunctor}.
Assuming that $C$ is pointed and denoting its \lstinline!cpure!
method by $\text{cpu}_{C}$, we can thus compute a value of type $P^{A}$
as $h(\text{cpu}_{C})$. To extract $A$ from $P^{A}$, we need to
assume additionally that $P$ is co-pointed and use its method $\text{ex}_{P}:P^{A}\rightarrow A$.
Finally we have
\begin{equation}
\text{ex}_{L}\triangleq h^{:C^{A}\rightarrow P^{A}}\rightarrow\text{ex}_{P}(h(\text{cpu}_{C}))\quad\quad\text{ or equivalently}\quad\quad h^{:C^{A}\rightarrow P^{A}}\triangleright\text{ex}_{L}=\text{cpu}_{C}\triangleright h\triangleright\text{ex}_{P}\quad.\label{eq:def-of-ex-for-C-mapsto-P}
\end{equation}
To verify the naturality law, we apply both sides to an arbitrary
$h^{:C^{A}\rightarrow P^{A}}$ and compute
\begin{align*}
{\color{greenunder}\text{expect to equal }h\triangleright\text{ex}_{L}\bef f:}\quad & h\triangleright f^{\uparrow L}\bef\text{ex}_{L}=(h\triangleright f^{\uparrow L})\,\gunderline{\triangleright\,\text{ex}_{L}}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:def-of-ex-for-C-mapsto-P})}:}\quad & =\text{cpu}_{C}\triangleright(h\triangleright f^{\uparrow L})\triangleright\text{ex}_{P}=\text{cpu}_{C}\triangleright\gunderline{(h\triangleright f^{\uparrow L})}\bef\text{ex}_{P}\\
{\color{greenunder}\text{definition of }f^{\uparrow L},\text{ see Eq.~(\ref{eq:f-functor-exponential-def-fmap-f-h})}:}\quad & =\text{cpu}_{C}\triangleright f^{\downarrow C}\bef h\bef\gunderline{f^{\uparrow P}\bef\text{ex}_{P}}\\
{\color{greenunder}\text{naturality law of }\text{ex}_{P}:}\quad & =\text{cpu}_{C}\triangleright f^{\downarrow C}\bef h\bef\text{ex}_{P}\bef f\quad.
\end{align*}
We expect the last expression to equal 
\[
h\triangleright\text{ex}_{L}\bef f=\text{cpu}_{C}\triangleright h\triangleright\text{ex}_{P}\triangleright f=\text{cpu}_{C}\triangleright h\bef\text{ex}_{P}\bef f\quad.
\]
This is possible only if $\text{cpu}_{C}\triangleright f^{\downarrow C}=\text{pu}_{C}$
for all $f$. This motivates us to assume that law as the \index{naturality law!of pure for contrafunctors@of \texttt{pure} for contrafunctors}\textbf{naturality
law} of $\text{cpu}_{C}$ for pointed contrafunctors. With that last
assumption, we have finished proving the naturality law of $\text{ex}_{L}$.
The code for $\text{ex}_{L}$ is
\begin{lstlisting}[mathescape=true]
def copointedFunc[C[_]: Pointed, P[_]: Copointed]: Copointed[Lambda[X => C[X] => P[X]]] =
  new Copointed[Lambda[X => C[X] => P[X]]] {
    def ex[A]: (C[A] => P[A]) => A = h => extract[P, A](h(cpure[C, A]))
  }      // In Scala 2.13: h => cpure[C, A] pipe h pipe extract[P, A] as in ${\color{dkgreen} h\rightarrow\text{pu}_{C}\triangleright h\triangleright\text{ex}_{P} }$
\end{lstlisting}

We will analyze pointed contrafunctors and their naturality law in
Section~\ref{subsec:Pointed-contrafunctors}.

\paragraph{Recursive types}

Consider a functor $F$ defined by a recursive equation $F^{A}\triangleq S^{A,F^{A}}$
where $S$ is a bifunctor (see Section~\ref{subsec:Bifunctors}).
The functor $F$ is co-pointed if a method $\text{ex}_{F}:(F^{A}\rightarrow A)\cong(S^{A,F^{A}}\rightarrow A)$
can be defined. Since the recursive definition of $F$ uses $F^{A}$
as a type argument in $S^{A,F^{A}}$, we may assume (by induction)
that an extractor function $F^{A}\rightarrow A$ is already available
when applied to the recursively used $F^{A}$. Then we can use the
\lstinline!bimap! method of $S$ to map $S^{A,F^{A}}\rightarrow S^{A,A}$.
It remains to extract a value of type $A$ out of a bifunctor value
$S^{A,A}$. We call a bifunctor $S$ \textbf{co-pointed}\index{co-pointed bifunctor}
if a fully parametric function $\text{ex}_{S}:S^{A,A}\rightarrow A$
exists and satisfies the corresponding \textbf{naturality law}:\index{naturality law!of co-pointed bifunctors}
\begin{equation}
\text{ex}_{S}\bef f=\text{bimap}_{S}(f)(f)\bef\text{ex}_{S}\quad.\label{eq:copointed-bifunctor-naturality-law}
\end{equation}
Assuming that $S$ is co-pointed, we can finally define $\text{ex}_{F}$
by recursion,
\[
\text{ex}_{F}\triangleq s^{:S^{A,F^{A}}}\rightarrow s\triangleright\big(\text{bimap}_{S}(\text{id})(\text{ex}_{F})\big)\triangleright\text{ex}_{S}\quad\text{ or equivalently}\quad\text{ex}_{F}\triangleq\text{bimap}_{S}(\text{id})(\text{ex}_{F})\bef\text{ex}_{S}\quad.
\]
To verify the naturality law of $\text{ex}_{F}$, we denote recursive
uses by an overline and compute:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{ex}_{F}\bef f:}\quad & \gunderline{f^{\uparrow F}}\bef\text{ex}_{F}\\
{\color{greenunder}\text{definition of }f^{\uparrow F},\text{ see Eq.~(\ref{eq:def-recursive-functor-fmap})}:}\quad & =\text{bimap}_{S}(f)(\overline{f^{\uparrow F}})\bef\gunderline{\text{ex}_{F}}\\
{\color{greenunder}\text{definition of }\text{ex}_{F}:}\quad & =\gunderline{\text{bimap}_{S}(f)(\overline{f^{\uparrow F}})\bef\text{bimap}_{S}(\text{id})(\overline{\text{ex}_{F}})}\bef\text{ex}_{S}\\
{\color{greenunder}\text{bifunctor composition law~(\ref{eq:f-bimap-composition-law})}:}\quad & =\text{bimap}_{S}(f\bef\text{id})(\overline{\gunderline{f^{\uparrow F}\bef\text{ex}_{F}}})\bef\text{ex}_{S}\\
{\color{greenunder}\text{naturality law of }\text{ex}_{F}:}\quad & =\gunderline{\text{bimap}_{S}(f)(\overline{\text{ex}_{F}\bef f})}\bef\text{ex}_{S}\\
{\color{greenunder}\text{bifunctor composition law in reverse}:}\quad & =\text{bimap}_{S}(\text{id})(\overline{\text{ex}_{F}})\bef\text{bimap}_{S}(f)(\overline{f})\bef\text{ex}_{S}\\
{\color{greenunder}\text{naturality law~(\ref{eq:copointed-bifunctor-naturality-law}) of }\text{ex}_{S}:}\quad & =\gunderline{\text{bimap}_{S}(\text{id})(\overline{\text{ex}_{F}})\bef\text{ex}_{S}}\bef f\\
{\color{greenunder}\text{definition of }\text{ex}_{F}:}\quad & =\text{ex}_{F}\bef f\quad.
\end{align*}
An example illustrating the recursive construction is the bifunctor
$S^{A,R}\triangleq A+R\times R$ that defines $F^{A}$ to be the binary
tree functor, 
\[
F^{A}\triangleq S^{A,F^{A}}=A+F^{A}\times F^{A}\quad.
\]
The bifunctor $S$ is co-pointed because there exists a suitable function
$\text{ex}_{S}:S^{A,A}\rightarrow A$.

\begin{wrapfigure}{l}{0.48\columnwidth}%
\vspace{0.35\baselineskip}
\begin{lstlisting}
type S[A, R] = Either[A, (R, R)]
def exS[A]: S[A, A] => A = {
  case Left(a)          => a
  case Right((a1, a2))  => a1  // Could be a2.
}
\end{lstlisting}

\vspace{-2.25\baselineskip}
\end{wrapfigure}%

\noindent In the code notation, the function $\text{ex}_{S}$ is written
as\vspace{-0.2\baselineskip}
\[
\text{ex}_{S}\triangleq\,\begin{array}{|c||c|}
 & A\\
\hline A & \text{id}\\
A\times A & \pi_{1}
\end{array}\quad.
\]
\vspace{-0.75\baselineskip}

\noindent This function extracts the left-most leaf of a binary tree
because it is using the projection $\pi_{1}$ (not $\pi_{2}$).

To implement the co-pointed instance $\text{ex}_{F}$ for the binary
tree functor, we need to use the implementation of $\text{bimap}_{S}$:
\begin{lstlisting}
def bimap_S[A,B,P,Q](f: A => B)(g: P => Q): S[A, P] => S[B, Q] = {
  case Left(a)         => Left(f(a))
  case Right((x, y))   => Right((g(x), g(y)))
}
\end{lstlisting}
Now we can define the recursive type constructor $F^{\bullet}$ and
a co-pointed instance for it:
\begin{lstlisting}
final case class F[A](s: S[A, F[A]])
val copointedF: Copointed[F] = new Copointed[F1] {
  def ex[A]: F1[A] => A = { case F1(s) => exS1(bimap_S(identity[A], ex[A])(s)) }
}
\end{lstlisting}

The naturality law holds for the recursive instance by induction (see
Section~\ref{subsec:The-Eq-typeclass}).

\paragraph{Summary}

Can we recognize a co-pointed functor $F$ by looking at its type
expression, e.g.
\[
F^{A,B}\triangleq\left(\left(\bbnum 1+A\rightarrow\text{Int}\right)\rightarrow A\times B\right)+\text{String}\times A\times A\quad?
\]
The constructions shown in this section tell us that a co-product
of two co-pointed functors is again co-pointed. Let us first check
whether $\text{String}\times A\times A$ is co-pointed. We can certainly
extract a value of type $A$ out of $\text{String}\times A\times A$,
but not a value of type $B$. So, there is no hope for $F^{A,B}$
to be co-pointed with respect to the parameter $B$.

It remains to consider $A$ as the type parameter. The type constructor
$\text{String}\times A\times A$ is co-pointed, but we still need
to check $\left(\bbnum 1+A\rightarrow\text{Int}\right)\rightarrow A\times B$,
which is a function type. The function construction requires $\bbnum 1+A\rightarrow\text{Int}$
to be a pointed contrafunctor and $A\times B$ to be a co-pointed
functor (with respect to $A$). It is clear that $A\times B$ is co-pointed
with respect to $A$ since we have $\pi_{1}:A\times B\rightarrow A$.
It remains to check that the contrafunctor $C^{A}\triangleq\bbnum 1+A\rightarrow\text{Int}$
is pointed. A contrafunctor $C^{\bullet}$ is pointed if values of
type $C^{\bbnum 1}$ can be computed (see Section~\ref{subsec:Pointed-contrafunctors});
this requires us to compute a value of type $\bbnum 1+\bbnum 1\rightarrow\text{Int}$.
One such value is \lstinline!{ _ => 0 }!, a constant function that
always returns the integer \lstinline!0!. 

We conclude that $F^{A,B}$ is co-pointed with respect to $A$ but
not co-pointed with respect to $B$.

\begin{table}
\begin{centering}
\begin{tabular}{|c|c|c|}
\hline 
\textbf{\footnotesize{}Construction} & \textbf{\footnotesize{}Type signature to implement} & \textbf{\footnotesize{}Results}\tabularnewline
\hline 
\hline 
{\footnotesize{}Identity functor} & {\footnotesize{}$\text{id}:A\rightarrow A$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Composition of co-pointed functors} & {\footnotesize{}$\text{Copointed}^{F^{\bullet}}\times\text{Copointed}^{G^{\bullet}}\rightarrow\text{Copointed}^{F^{G^{\bullet}}}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Product of co-pointed functor $F$ and any $G$} & {\footnotesize{}$\text{Copointed}^{F^{\bullet}}\times\text{Functor}^{G^{\bullet}}\rightarrow\text{Copointed}^{F^{\bullet}\times G^{\bullet}}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Co-product of co-pointed functors $F$ and $G$} & {\footnotesize{}$\text{Copointed}^{F^{\bullet}}\times\text{Copointed}^{G^{\bullet}}\rightarrow\text{Copointed}^{F^{\bullet}+G^{\bullet}}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Function from pointed $C$ to co-pointed $F$} & {\footnotesize{}$\text{\ensuremath{\text{Pointed}^{C^{\bullet}}}}\times\text{Copointed}^{F^{\bullet}}\rightarrow\text{Copointed}^{C^{\bullet}\rightarrow F^{\bullet}}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Recursive type} & {\footnotesize{}$\text{Copointed}^{F^{\bullet}}\rightarrow\text{Copointed}^{S^{\bullet,F^{\bullet}}}$
where $F^{A}\triangleq S^{A,F^{A}}$} & {\footnotesize{}$\text{Copointed}^{F^{\bullet}}$}\tabularnewline
\hline 
\end{tabular}
\par\end{centering}
\caption{Type constructions producing the \lstinline!Copointed! functor typeclass.\label{tab:Type-constructions-for-copointed-functor}}
\end{table}


\subsection{Pointed contrafunctors\label{subsec:Pointed-contrafunctors}}

In the previous section, the function-type construction required a
contrafunctor $C^{\bullet}$ to have a method $\text{cpu}_{C}$ of
type $\forall A.\,C^{A}$; we called such contrafunctors \textbf{pointed}.
We also needed to assume that the naturality law holds for all functions
$f^{:A\rightarrow B}$, 
\begin{equation}
\text{cpu}_{C}\triangleright f^{\downarrow C}=\text{cpu}_{C}\quad\text{ or equivalently }\quad\text{cmap}_{C}(f^{:A\rightarrow B})(\text{cpu}_{C}^{:C^{B}})=\text{cpu}_{C}^{:C^{A}}\quad.\label{eq:naturality-law-for-pure-for-contrafunctors}
\end{equation}
\[
\xymatrix{\xyScaleY{2.0pc}\xyScaleX{3.0pc}\text{cpu}_{C}:C^{B}\ar[d]\sb(0.5){\text{cmap}_{C}(f)} & B\\
\text{cpu}_{C}:C^{A} & A\ar[u]\sp(0.5){~f}
}
\]
We may simplify the formulation of the typeclass by setting $B=\bbnum 1$
in the naturality law~(\ref{eq:naturality-law-for-pure-for-contrafunctors})
and denoting $\text{wu}_{C}\triangleq\text{cpu}_{C}^{\bbnum 1}$.
The law~(\ref{eq:naturality-law-for-pure-for-contrafunctors}) then
gives 
\begin{equation}
\text{cpu}_{C}^{A}=\text{wu}_{C}\triangleright(\_^{:A}\rightarrow1)^{\downarrow C}\quad.\label{eq:def-pure-via-wu-for-contrafunctor}
\end{equation}
In this way, we express the \lstinline!cpure! method through a chosen
value $\text{wu}_{C}:C^{\bbnum 1}$. For the same reasons as in the
case of pointed functors, the types of $\text{cpu}_{C}$ and $\text{wu}_{C}$
are equivalent. The law~(\ref{eq:naturality-law-for-pure-for-contrafunctors})
for $\text{cpu}_{C}$ will be satisfied automatically if $\text{cpu}_{C}$
is defined via Eq. (\ref{eq:def-pure-via-wu-for-contrafunctor}).
To verify that, compute
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{cpu}_{C}^{A}:}\quad & \text{cpu}_{C}^{B}\triangleright f^{\downarrow C}\\
{\color{greenunder}\text{use definition~(\ref{eq:def-pure-via-wu-for-contrafunctor})}:}\quad & =\text{wu}_{C}\triangleright\gunderline{(\_^{:B}\rightarrow1)^{\downarrow C}\triangleright f^{\downarrow C}}\\
{\color{greenunder}\text{composition law of contrafunctor }C:}\quad & =\text{wu}_{C}\triangleright(\gunderline{f\bef(\_^{:B}\rightarrow1)})^{\downarrow C}\\
{\color{greenunder}\text{compute function composition}:}\quad & =\text{wu}_{C}\triangleright(\_^{:A}\rightarrow1)^{\downarrow C}=\text{cpu}_{C}^{A}\quad.
\end{align*}
So, a pointed contrafunctor instance for $C^{\bullet}$ is equivalent
to a chosen value of type $C^{\bbnum 1}$.
\begin{lstlisting}
final case class Pointed[F[_]](wu: F[Unit])
def cpure[F[_]: Pointed : Contrafunctor, A]: F[A] = implicitly[Pointed[F]].wu.cmap(_ => ())
\end{lstlisting}
Here we used a \lstinline!Contrafunctor! typeclass (see Example~\ref{subsec:tc-Example-6}
below). We can now apply structural analysis to pointed contrafunctors,
similarly to Section~\ref{subsec:f-Contrafunctor-constructions}.
The results are shown in Table~\ref{tab:Type-constructions-for-pointed-contrafunctor}.

\paragraph{Fixed types}

This construction is the same as for pointed functors (Section~\ref{subsec:Pointed-functors:-structural-analysis}).
A fixed type $Z$ gives a constant contrafunctor $C^{A}\triangleq Z$.
Since $C^{\bbnum 1}=Z$, the constant contrafunctor is pointed if
we have a chosen value of type $Z$; this will be the case, for instance,
if $Z=\bbnum 1+U$ for some type $U$. 

\paragraph{Type parameters}

Since the identity functor $\text{Id}^{A}\triangleq A$ is not a contrafunctor,
it remains to consider the functor compositions $C^{F^{A}}$ and $F^{C^{A}}$
where $C^{\bullet}$ is a contrafunctor and $F^{\bullet}$ is a functor. 

If $C$ is pointed, we can always obtain a value $\text{cpu}_{C}$
of type $C^{A}$ for any type $A$, in particular for $A=F^{\bbnum 1}$
(whether or not a value of type $F^{\bbnum 1}$ can be computed).
So, $C^{F^{\bullet}}$ is a pointed contrafunctor whenever $C^{\bullet}$
is one, for any (not necessarily pointed) functor $F$.
\begin{lstlisting}
def pointedCoF[C[_]: Pointed: Contrafunctor, F[_]]: Pointed[Lambda[X => C[F[X]]]] =
  Pointed[Lambda[X => C[F[X]]]](cpure[C, F[Unit]])
\end{lstlisting}

Creating a value of type $F^{C^{\bbnum 1}}$ requires $F$ to have
a \lstinline!pure! method that could be applied to a value of type
$C^{\bbnum 1}$ to compute a value of type $F^{C^{\bbnum 1}}$. So,
$F^{C^{\bullet}}$ is pointed whenever both $C^{\bullet}$ and $F^{\bullet}$
are pointed.
\begin{lstlisting}
def pointedFoC[C[_]: Pointed, F[_]: Pointed : Functor]: Pointed[Lambda[X => F[C[X]]]] =
  Pointed[Lambda[X => F[C[X]]]](pure[F, C[Unit]](implicitly[Pointed[C]].wu))
\end{lstlisting}


\paragraph{Products}

The construction is the same as for pointed functors: If we have values
of type $C^{\bbnum 1}$ and $D^{\bbnum 1}$, we can compute the pair
$C^{\bbnum 1}\times D^{\bbnum 1}$. This makes the product contrafunctor
$L^{A}\triangleq C^{A}\times D^{A}$ pointed if both $C^{\bullet}$
and $D^{\bullet}$ are pointed contrafunctors.

\paragraph{Co-products}

The construction is the same as for pointed functors: If at least
one of the contrafunctors $C^{\bullet}$ and $D^{\bullet}$ is pointed,
we can create a \lstinline!Pointed! instance for the co-product contrafunctor
$L^{A}\triangleq C^{A}+D^{A}$ as either $\text{wu}_{L}=\text{wu}_{C}+\bbnum 0^{:D^{\bbnum 1}}$
or $\text{wu}_{L}=\bbnum 0^{:C^{\bbnum 1}}+\text{wu}_{D}$.

\paragraph{Functions}

The exponential contrafunctor construction is $L^{A}\triangleq F^{A}\rightarrow C^{A}$,
where $C^{\bullet}$ is a contrafunctor and $F^{\bullet}$ is a functor.
To create a value $\text{wu}_{L}:L^{\bbnum 1}$ means to create a
function of type $F^{\bbnum 1}\rightarrow C^{\bbnum 1}$. That function
cannot use its argument of type $F^{\bbnum 1}$ for computing a value
$C^{\bbnum 1}$ since $F$ is an arbitrary functor. So, $\text{wu}_{L}$
must be a constant function $(\_^{:F^{\bbnum 1}}\rightarrow\text{wu}_{C})$,
where we assumed that a value $\text{wu}_{C}:C^{\bbnum 1}$ is available.
Thus, $F^{A}\rightarrow C^{A}$ is pointed when $C$ is a pointed
contrafunctor and $F$ is any functor.
\begin{lstlisting}
def pointedFuncFC[C[_]: Pointed, F[_]]: Pointed[Lambda[X => F[X] => C[X]]] =
      Pointed[Lambda[X => F[X] => C[X]]](_ => implicitly[Pointed[C]].wu)
\end{lstlisting}


\paragraph{Recursive types}

The recursive construction for contrafunctors (see Statement~\ref{subsec:functor-Statement-contrafunctor-recursive-1})
is $C^{A}\triangleq S^{A,C^{A}}$ where $S^{A,R}$ is a contrafunctor
in $A$ and a functor in $R$. Values of type $C^{\bbnum 1}$ will
exist when the recursive type equation $T\triangleq S^{\bbnum 1,T}$
defines a non-void type $T$. This condition is similar to that for
pointed functors, and the resulting construction is the same.

\paragraph{Summary}

Can we recognize a pointed contrafunctor $C$ by looking at its type
expression, e.g.
\[
C^{A,B}\triangleq\left(\bbnum 1+A\rightarrow B\right)+(\text{String}\times A\times B\rightarrow\text{String})\text{ with respect to type parameter }A?
\]
We need to set $A=\bbnum 1$ and try to create a value $\text{wu}:C^{\bbnum 1,B}$.
In this example, $C^{\bbnum 1,B}=\left(\bbnum 1+\bbnum 1\rightarrow B\right)+(\text{String}\times\bbnum 1\times B\rightarrow\text{String})$.
A value of this type is $\text{wu}_{C}\triangleq\bbnum 0+(s^{:\text{String}}\times1\times b^{:B}\rightarrow s)$.
So, the contrafunctor $C^{A,B}$ is pointed with respect to $A$.

\begin{table}
\begin{centering}
\begin{tabular}{|c|c|c|}
\hline 
\textbf{\footnotesize{}Construction} & \textbf{\footnotesize{}Type signature to implement} & \textbf{\footnotesize{}Results}\tabularnewline
\hline 
\hline 
{\footnotesize{}Constant functor returning a fixed type $Z$} & {\footnotesize{}value of type $Z$} & {\footnotesize{}$Z$ has a default}\tabularnewline
\hline 
{\footnotesize{}Composition of pointed functors/contrafunctors} & {\footnotesize{}$\text{Pointed}^{F^{\bullet}}\times\text{Pointed}^{G^{\bullet}}\rightarrow\text{Pointed}^{F^{G^{\bullet}}}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Product of pointed contrafunctors $F$ and $G$} & {\footnotesize{}$\text{Pointed}^{F^{\bullet}}\times\text{Pointed}^{G^{\bullet}}\rightarrow\text{Pointed}^{F^{\bullet}\times G^{\bullet}}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Co-product of a pointed $F$ and any $G$} & {\footnotesize{}$\text{Pointed}^{F^{\bullet}}\times\text{Contrafunctor}^{G^{\bullet}}\rightarrow\text{Pointed}^{F^{\bullet}+G^{\bullet}}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Function from a functor $F$ to a pointed $C$} & {\footnotesize{}$\text{Pointed}^{C^{\bullet}}\times\text{Functor}^{F^{\bullet}}\rightarrow\text{Pointed}^{F^{\bullet}\rightarrow C^{\bullet}}$} & {\footnotesize{}one possibility}\tabularnewline
\hline 
{\footnotesize{}Recursive type} & {\footnotesize{}$\text{Pointed}^{C^{\bullet}}\rightarrow\text{Pointed}^{S^{\bullet,C^{\bullet}}}$
where $C^{A}\triangleq S^{A,C^{A}}$} & {\footnotesize{}$\text{Pointed}^{C^{\bullet}}$}\tabularnewline
\hline 
\end{tabular}
\par\end{centering}
\caption{Type constructions producing the \lstinline!Pointed! contrafunctor
typeclass.\label{tab:Type-constructions-for-pointed-contrafunctor}}
\end{table}


\section{Summary}

What problems can we solve now?
\begin{itemize}
\item Define arbitrary PTVFs using typeclass constraints on type parameters.
\item Define typeclasses and typeclass instances for types and for type
constructors.
\item Implement \lstinline!Monoid!, \lstinline!Functor!, and other standard
typeclasses, and prove their laws.
\item Use known constructions to derive typeclass instances from previous
ones.
\end{itemize}
What problems cannot be solved with these tools?
\begin{itemize}
\item \emph{Automatically} derive type class instances for given data types
or type constructors.
\item Combine typeclasses and express dependencies, e.g., typeclass \lstinline!TC1!
requires \lstinline!TC2! and \lstinline!TC3!.
\end{itemize}
We may want to write code such as
\begin{lstlisting}
type F[A] = (A => Int) => A                     // Define a type constructor.
implicit val functorF: Functor[F] = implement   // Automatically implement typeclass instance for F.
implicit val pointedF: Pointed[F] = implement   // Automatically use the function-type construction.
\end{lstlisting}
However, no currently available library provides such functionality.
Also, typeclass instances are not always derived uniquely, as we have
seen in several cases (e.g., the co-product construction of monoids
or pointed functors).

We will discuss how to combine typeclasses in Section~\ref{subsec:Inheritance-and-automatic-typeclass}
below.

\subsection{Solved examples\index{solved examples}}

\subsubsection{Example \label{subsec:tc-Example-1}\ref{subsec:tc-Example-1}}

Define a PTVF with type signature \lstinline!def bitsize[T]: Int!
such that \lstinline!bitsize[Short]! returns $16$, \lstinline!bitsize[Int]!
returns $32$, and \lstinline!bitsize[Long]! returns $64$. For all
other types \lstinline!T!, the expression \lstinline!bitsize[T]!
should remain undefined.

\subparagraph{Solution}

The function \lstinline!bitsize[T]! needs to take an additional implicit
argument that will be available only for \lstinline!T = Short!, \lstinline!T = Int!,
and \lstinline!T = Long!. To implement that, we need to define a
new type constructor, say \lstinline!HasBitsize[T]!, and create implicit
values of the corresponding types. The new type constructor defines
a typeclass whose instances need to carry the information about the
bit size:
\begin{lstlisting}
final case class HasBitsize[T](size: Int)
object HasBitsize {
  implicit val bitsizeShort = HasBitsize[Short](16)
  implicit val bitsizeInt   = HasBitsize[Int]  (32)
  implicit val bitsizeLong  = HasBitsize[Long] (64)
}
\end{lstlisting}
Now we can define the function \lstinline!bitsize! as a PTVF,
\begin{lstlisting}
def bitsize[T](implicit ti: HasBitsize[T]): Int = ti.size
\end{lstlisting}
The instance argument such as \lstinline!ti: HasBitsize[T]! is sometimes
called the \textsf{``}evidence\textsf{''}\index{evidence value} argument\index{typeclass!evidence argument}
because its presence provides \textsf{``}evidence\textsf{''} that the type \lstinline!T!
belongs to the type domain of the typeclass.

We can check that the function \lstinline!bitsize! is defined only
for supported types:
\begin{lstlisting}
scala> bitsize[Long]
res0: Int = 64

scala> bitsize[String]
<console>:15: error: could not find implicit value for evidence parameter of type HasBitsize[String]
       bitsize[String]
              ^ 
\end{lstlisting}

The current implementation of \lstinline!HasBitsize! allows the programmer
to add new types to its type domain whenever necessary. For example,
the following code will add support for the \lstinline!Boolean! type
so that \lstinline!bitsize[Boolean]! will evaluate to \lstinline!1!:
\begin{lstlisting}
implicit val bitsizeBoolean = HasBitsize[Boolean](1)
\end{lstlisting}
In some applications, it is important that the type domain of a PTVF
should remain fixed (e.g., as defined in a library). To prevent the
programmer from creating any further values of type \lstinline!HasBitsize!,
we could make it a non-case class whose constructor is declared as
a \lstinline!private! function like this:
\begin{lstlisting}
final class HasBitsize[T] private (val size: Int) // Not a case class; the constructor is private.
object HasBitsize {            // The companion object is allowed to call the private constructor.
  implicit val bitsizeShort = new HasBitsize[Short](16)
  implicit val bitsizeInt   = new HasBitsize[Int]  (32)
  implicit val bitsizeLong  = new HasBitsize[Long] (64)
}
\end{lstlisting}
The code of \lstinline!bitsize[T]! remains unchanged. With these
definitions, no further typeclass instances can be created by any
code outside of the companion object \lstinline!HasBitsize!:
\begin{lstlisting}
scala> implicit val bitsizeBoolean = new HasBitsize[Boolean](1)
<console>:16: error: constructor HasBitsize in class HasBitsize cannot be accessed in object $iw
       implicit val bitsizeBoolean = new HasBitsize[Boolean](1)
                                     ^
\end{lstlisting}

An implementation via a \lstinline!trait! requires longer code but
brings no significant advantages:
\begin{lstlisting}
trait HasBitsize[T] { def size: Int } // Declare the trait as `sealed` to prohibit further instances.
object HasBitsize {
  implicit val bitsizeShort = new HasBitsize[Short]{ def size: Int = 16 }
  implicit val bitsizeInt   = new HasBitsize[Int]  { def size: Int = 32 }
  implicit val bitsizeLong  = new HasBitsize[Long] { def size: Int = 64 }
}
\end{lstlisting}


\subsubsection{Example \label{subsec:tc-Example-2}\ref{subsec:tc-Example-2}}

Define a \lstinline!Monoid! instance for the type $\bbnum 1+(\text{String}\rightarrow\text{String})$.

\subparagraph{Solution}

We look for suitable monoid constructions (Section~\ref{subsec:Monoids-constructions})
that build up the given type expression from simpler parts. Since
the type expression $\bbnum 1+(\text{String}\rightarrow\text{String})$
is a co-product at the outer level, we must start with the co-product
construction, which requires us to choose one of the parts of the
disjunction, say $\text{String}\rightarrow\text{String}$, as the
\textsf{``}preferred\textsf{''} monoid. Next, we need to produce \lstinline!Monoid!
instances for $\bbnum 1$ and for $\text{String}\rightarrow\text{String}$.
While the \lstinline!Unit! type has a unique \lstinline!Monoid!
instance, there are several for $\text{String}\rightarrow\text{String}$.
The function-type construction gives two possible monoid instances:
the monoid $R\rightarrow A$ with $R=A=\text{String}$, and the function
composition monoid. Let us choose the latter. The code using the monoid
constructions from Section~\ref{subsec:Monoids-constructions} can
then be written as
\begin{lstlisting}
val monoidX: Monoid[Either[Unit, String => String]] = {
  implicit val m1 = Monoid[Unit]( (x, y) => (), () )
  implicit val m2: Monoid[String => String] = monoidFunc1[String]
  monoidEitherPreferB[Unit, String => String]
)
\end{lstlisting}
We can translate the constructions into code for a \lstinline!Monoid!
instance for the type \lstinline!Option[String => String]!:
\begin{lstlisting}
val monoidX: Monoid[Option[String => String]] = Monoid( {
  case (None, None)         => None
  case (None, Some(f))      => Some(f)
  case (Some(f), None)      => Some(f)
  case (Some(f), Some(g))   => Some(f andThen g)
}, None )
\end{lstlisting}


\subsubsection{Example \label{subsec:tc-Example-3}\ref{subsec:tc-Example-3}}

Show that if $A$ is a monoid and $B$ is a semigroup then $A+B$
is a monoid.

\subparagraph{Solution}

The co-product construction  $A+B$ (where both $A$, $B$ are monoids)
has two implementations: one of the empty elements $e_{A}$ or $e_{B}$
must be chosen as the empty element for the monoid $A+B$. If $B$
is not a monoid, the only choice is to set $e_{A+B}\triangleq e_{A}+\bbnum 0$.
This is the implementation in the function \lstinline!monoidEitherPreferB!
(Section~\ref{subsec:Monoids-constructions}). We just need to replace
the \lstinline!Monoid! typeclass constraint for $B$ by \lstinline!Semigroup!:
\begin{lstlisting}
def monoidEitherSemigroup[A: Monoid, B: Semigroup] = Monoid[Either[A, B]]( {
  case (Left(a1), Left(a2))     => Left(a1 |+| a2)
  case (Left(a), Right(b))      => Right(b) // "Take B".
  case (Right(b), Left(a))      => Right(b)
  case (Right(b1), Right(b2))   => Right(b1 |+| b2)
}, Left(implicitly[Monoid[A]].empty) ) // The type B does not need an empty element.
\end{lstlisting}
The monoid laws hold here because the proofs of the laws do not depend
on the existence of $e_{B}$.

\subsubsection{Example \label{subsec:tc-Example-4}\ref{subsec:tc-Example-4} (a
routing monoid)}

A (much simplified) web server is implemented as a number of \textsf{``}routes\textsf{''}.
Each route may respond to one or more URL paths by evaluating a custom
function. The task is to implement a \lstinline!combine! operation
for routes. The combined route should respond to all paths that at
least one of the previous routes responds to:
\begin{lstlisting}
type Path = String              //    Here, the types `Path` and `Response` are defined only as an
type Response = (Int, String)   // illustration. The code will use these types as type parameters.

type Route = Path => Option[Response]

val r1: Route = { case "/get_users" => (200, "user1, user2, user3") }
val r2: Route = { case "/get_names" => (200, "name1, name2, name3") }
      // The task is to implement an extension method |+| such that this works correctly:
val route: Route = r1 |+| r2     // Should respond to both `/get_users` and `/get_names`.
\end{lstlisting}
Use the \texttt{cats} library for implementing a \lstinline!Monoid!
instance for routes; verify that the monoid laws hold.

\paragraph{Solution}

We will first figure out how to implement the required functionality,
and then adapt the code to the \texttt{cats} library\textsf{'}s definition
of the \lstinline!Monoid! typeclass.

A \textsf{``}route\textsf{''} is a function of type \lstinline!Path => Option[Response]!
that returns a non-empty option if the route responds to a given path
value. A combination of two routes \lstinline!r1! and \lstinline!r2!
needs to be a new route, i.e., a function \lstinline!Path => Option[Response]!.
The new function will first check whether \lstinline!r1! responds
to a given path. If so, it will evaluate the result of applying \lstinline!r1!.
Otherwise, it will try applying \lstinline!r2! to the given path.
We implement the required business logic in a function called \lstinline!combineRoutes!:
\begin{lstlisting}
def combineRoutes(r1: Route, r2: Route): Route = { path =>
  r1(path) match {
    case Some(response) => Some(response)
    case None => r2(path)
  }
}
\end{lstlisting}

A monoid also needs to have an empty element. An \textsf{``}empty route\textsf{''}
can be combined with any other route and will not change the behavior
of that route. If the empty route responds to any path, it would prevent
another route from also responding to the same path. So, the only
solution is to define the \textsf{``}empty route\textsf{''} as a function that \emph{never}
responds to any path:
\begin{lstlisting}
val emptyRoute: Route = { _ => None }
\end{lstlisting}

The \texttt{cats} library defines the \lstinline!Monoid! typeclass
via a \lstinline!trait! with methods \lstinline!empty! and \lstinline!combine!.
We can define that typeclass using our existing code:
\begin{lstlisting}
import $ivy.`org.typelevel::cats-core:1.5.0`, cats.Monoid      // Using `ammonite` for convenience.
implicit val catsMonoidRoute: Monoid[Route] = new Monoid[Route] {
  def empty: Route = emptyRoute
  def combine(x: Route, y: Route): Route = combineRoutes(x, y)
}
\end{lstlisting}
We can now check that the routes can be combined as we intended:
\begin{lstlisting}
import cats.syntax.monoid._
val route: Route = r1 |+| r2

ammonite@ route("/get_users")
res0: Response = (200, "user1, user2, user3")

ammonite@ route("/get_names")
res1: Response = (200, "name1, name2, name3")
\end{lstlisting}

To verify that the monoid laws hold, we could look for direct proofs
using the code of \lstinline!emptyRoute! and \lstinline!combineRoutes!.
However, it is easier to figure out how to reduce the definition of
the \lstinline!Route! monoid to a number of constructions listed
in Section~\ref{subsec:Monoids-constructions}. 

For more convenient reasoning, we replace the types \lstinline!Path!
and \lstinline!Response! by type parameters $P$ and $R$. We note
that these types are used fully parametrically by the code of our
functions. So, we will write the type \lstinline!Route! as $\text{Route}\triangleq P\rightarrow\bbnum 1+R$.
Since \lstinline!Route! is a function type at the outer level, we
start with the function-type construction, which requires $\bbnum 1+R$
to be a monoid. This suggests using the co-product construction; however,
$R$ is not necessarily a monoid. There are several possible monoid
instances for $\bbnum 1+R$, so let us look at how the code of \lstinline!combineRoutes!
handles values of that type. The value $1+\bbnum 0^{:R}$ corresponds
to a route that is not responding to a given path; in that case, \lstinline!combineRoutes!
will switch to the other route. So, the empty value of the monoid
$\bbnum 1+R$ must be $1+\bbnum 0^{:R}$. This is indeed the value
returned by \lstinline!emptyRoute! when applied to any path.

A non-empty value $\bbnum 0+r$ corresponds to a route that responds
to a given path; given two such values, \lstinline!combineRoutes!
will take the first one. This corresponds to the binary operation
$\oplus_{R}$ defined by $r_{1}\oplus_{R}r_{2}=r_{1}$. This operation
makes $R$ into a trivial semigroup (see Section~\ref{subsec:Semigroups-constructions}).
As Example~\ref{subsec:tc-Example-3} showed, $\bbnum 1+R$ is a
monoid if $R$ is a semigroup (since the unit type $\bbnum 1$ is
a monoid).

So, we have reduced the monoid instance defined by \lstinline!emptyRoute!
and \lstinline!combineRoutes! to a trivial semigroup, a co-product
construction, and a function-type construction. Since all those constructions
are guaranteed to produce lawful monoids, we do not need to prove
the monoid laws by hand.

\subsubsection{Example \label{subsec:tc-Example-4-1}\ref{subsec:tc-Example-4-1}}

Using the \texttt{cats} library, define a \lstinline!Functor! instance
for the type \lstinline!Seq[Try[T]]!.

\subparagraph{Solution}

The \texttt{cats} library defines the \lstinline!Functor! typeclass
as a \lstinline!trait! with a \lstinline!map! method,
\begin{lstlisting}
trait Functor[F[_]] { def map[A, B](fa: F[A])(f: A => B): F[B] }
\end{lstlisting}
The functor \lstinline!Seq[Try[T]]! is a composition of functors
\lstinline!Seq! and \lstinline!Try!, so we can define the \lstinline!map!
method for it using the functor composition (see Statement~\ref{subsec:functor-Statement-functor-composition-1}).
We wrap \lstinline!Seq[Try[T]]! into a case class:
\begin{lstlisting}
import cats.Functor
final case class F[T](s: Seq[Try[T]]) // `type F[T] = Seq[Try[T]]` does not work with `map` method.
implicit val functorF: Functor[F] = new Functor[F] {
  def map[A, B](fa: F[A])(f: A => B): F[B] = F(fa.s.map(_.map(f)))
}
\end{lstlisting}
One more \texttt{cats}-specific import is necessary to enable the
\lstinline!map! extension method for functors:
\begin{lstlisting}
import cats.syntax.functor._      // Enable the `map` method.
val s = F(Seq(Try(1), Try(2), Try(3)))

ammonite@ s.map(_ * 10)
res0: F[Int] = F(List(Success(10), Success(20), Success(30)))
\end{lstlisting}
For the \lstinline!map! method to work, the type constructor \lstinline!F!
must be defined as a \lstinline!class! or a \lstinline!trait!. Defining
\lstinline!F! as a type alias would make the Scala compiler confused:
if the type \lstinline!F[T]! were \emph{the same} as \lstinline!Seq[Try[T]]!,
the expression \lstinline!Seq(Try(1)).map(_ * 10)! would mean to
apply \lstinline!Seq!\textsf{'}s built-in \lstinline!map! method rather than
the extension method \lstinline!map! defined for the type constructor
\lstinline!F! via the \lstinline!Functor! typeclass.

\subsubsection{Example \label{subsec:tc-Example-5}\ref{subsec:tc-Example-5}}

Using the \texttt{cats} library, implement a \lstinline!Bifunctor!
instance for $Q^{X,Y}\triangleq X+X\times Y$.

\subparagraph{Solution}

The \texttt{cats} library defines the \lstinline!Bifunctor! \index{typeclass!Bifunctor@\texttt{Bifunctor}}typeclass
as a \lstinline!trait! with the \lstinline!bimap! method. Implementing
that method as an information-preserving, fully parametric function
is straightforward:
\begin{lstlisting}
final case class Q[X, Y](q: Either[X, (X, Y)])
implicit val bifunctorQ = new Bifunctor[Q] {
  def bimap[A, B, C, D](fab: Q[A, B])(f: A => C, g: B => D): Q[C, D] = fab.q match {
    case Left(a)         => Q(Left(f(a)))
    case Right((a, b))   => Q(Right((f(a), g(b))))
  }
}
\end{lstlisting}


\subsubsection{Example \label{subsec:tc-Example-6}\ref{subsec:tc-Example-6}}

Define a \lstinline!Contrafunctor! typeclass having the method \lstinline!contramap!
(see Section~\ref{subsec:Contrafunctors}):\index{typeclass!Contrafunctor@\texttt{Contrafunctor}}
\begin{lstlisting}
def contramap[A, B](c: C[A])(f: B => A): C[B]
\end{lstlisting}
Implement a \lstinline!Contrafunctor! instance for the type constructor
$C^{A}\triangleq A\rightarrow\text{Int}$.

\subparagraph{Solution}

Since the typeclass method has type parameters, the instance value
will have type
\[
\text{contramap}:\forall(A,B).\,C^{A}\rightarrow(B\rightarrow A)\rightarrow C^{B}\quad.
\]
So, the typeclass needs to be implemented as a \lstinline!trait!:
\begin{lstlisting}
trait Contrafunctor[C[_]] { def contramap[A, B](c: C[A])(f: B => A): C[B] }
\end{lstlisting}
A typeclass instance for the type constructor $C^{A}\triangleq A\rightarrow\text{Int}$
is created by
\begin{lstlisting}
type C[A] = A => Int
implicit val contrafunctorC = new Contrafunctor[C] {
  def contramap[A, B](c: A => Int)(f: B => A): B => Int = f andThen c
}
\end{lstlisting}

The \texttt{cats} library defines an equivalent typeclass named \lstinline!Contravariant!
with the method \lstinline!contramap!.

\subsubsection{Example \label{subsec:tc-Example-7}\ref{subsec:tc-Example-7}}

Define a \lstinline!Functor! instance for recursive type constructor
$Q^{A}\triangleq\left(\text{Int}\rightarrow A\right)+\text{Int}+Q^{A}$.

\subparagraph{Solution}

Begin by defining $Q^{A}$ as a recursive disjunctive type:
\begin{lstlisting}
sealed trait Q[A]
final case class C1[A](i: Int => A) extends Q[A]
final case class C2[A](x: Int)      extends Q[A]
final case class C3[A](q: Q[A])     extends Q[A]
\end{lstlisting}
The methods of Section~\ref{subsec:f-Functor-constructions} show
how to implement the \lstinline!map! function for \lstinline!Q[A]!.
Without repeating those steps, we will write code for a \lstinline!Functor!
instance directly:
\begin{lstlisting}
implicit val functorQ: Functor[Q] = new Functor[Q] { // The function `map` is recursive.
  def map[A, B](qa: Q[A])(f: A => B): Q[B] = qa match {
    case C1(i)   => C1(i andThen f)
    case C2(x)   => C2(x)
    case C3(q)   => C3(map(q)(f)) // Recursive case.
  }
}
\end{lstlisting}


\subsubsection{Example \label{subsec:tc-Example-8}\ref{subsec:tc-Example-8}}

Using a function parameterized by the type constructors $F$ and $G$
(required to be functors), implement a \lstinline!Functor! instance
for $F^{A}+G^{A}$.

\subparagraph{Solution}

The co-product construction (Statement~\ref{subsec:functor-Statement-functor-coproduct})
shows how to implement the \lstinline!map! function for the functor
$F^{A}+G^{A}$. We begin by writing code for a \lstinline!Functor!
instance assuming that the type constructors \lstinline!F! and \lstinline!G!
are given:
\begin{lstlisting}
type L[A] = Either[F[A], G[A]]
implicit val functorEither = new Functor[L] {
  def map[A, B](e: L[A])(f: A => B): L[B] = e match {
    case Left(fa)    => Left(fa.map(f))
    case Right(ga)   => Right(ga.map(f))
  }
}
\end{lstlisting}
We will now to rewrite this code by making \lstinline!F! and \lstinline!G!
into type parameters. To achieve that, we need to use the \textsf{``}kind
projector\index{kind@\textsf{``}kind projector\textsf{''} plugin}\textsf{''} plugin and replace
the type constructor \lstinline!L! by a nameless type function \lstinline!Lambda[X => Either[F[X], G[X]]]!.
The code becomes
\begin{lstlisting}
implicit def functorEither[F[_], G[_]] = new Functor[Lambda[X => Either[F[X], G[X]]]] {
  type L[A] = Either[F[A], G[A]]         // We may use F and G to define a type alias in this scope.
  def map[A, B](e: L[A])(f: A => B): L[B] = e match {
    case Left(fa)    => Left(fa.map(f))
    case Right(ga)   => Right(ga.map(f))
  }
}
\end{lstlisting}


\subsubsection{Example \label{subsec:tc-Example-10}\ref{subsec:tc-Example-10}{*}}

\textbf{(a)} Implement a function with type signature $C^{A}+C^{B}\rightarrow C^{A\times B}$
parameterized by a type constructor $C$ (required to be a contrafunctor)
and by arbitrary types $A$, $B$. Show that the inverse type signature
$C^{A\times B}\rightarrow C^{A}+C^{B}$ is not implementable for some
contrafunctors $C$.

\textbf{(b)} Implement a function with type signature $F^{A\times B}\rightarrow F^{A}\times F^{B}$
parameterized by a type constructor $F$ (required to be a functor)
and by arbitrary types $A$, $B$. Show that the inverse type signature
$F^{A}\times F^{B}\rightarrow F^{A\times B}$ is not implementable
for some functors $F$.

\subparagraph{Solution}

\textbf{(a)} We need to implement a function with type signature
\[
\forall(A,B).\,C^{A}+C^{B}\rightarrow C^{A\times B}\quad.
\]
Begin by looking at the types involved. We need to relate values $C^{A\times B}$,
$C^{A}$, and $C^{B}$; can we relate $A\times B$, $A$, and $B$?
There exist unique fully parametric functions $\pi_{1}$ and $\pi_{2}$
of types $A\times B\rightarrow A$ and $A\times B\rightarrow B$.
If we lift these functions to the contrafunctor $C$, we will get
$\pi_{1}^{\downarrow C}:C^{A}\rightarrow C^{A\times B}$ and $\pi_{2}^{\downarrow C}:C^{B}\rightarrow C^{A\times B}$.
The required type signature is then implemented via a \lstinline!match!
expression like this:

\begin{wrapfigure}{l}{0.58\columnwidth}%
\vspace{-0.75\baselineskip}
\begin{lstlisting}
def f[C[_]: Contrafunctor, A, B]
               : Either[C[A], C[B]] => C[(A, B)] = {
  case Left(ca)    => ca.contramap { case (a, b) => a }
  case Right(cb)   => cb.contramap { case (a, b) => b }
}
\end{lstlisting}

\vspace{-3\baselineskip}
\end{wrapfigure}%

\noindent The code notation for this function is\vspace{-0.25\baselineskip}
\[
f^{:C^{A}+C^{B}\rightarrow C^{A\times B}}\triangleq\,\begin{array}{|c||c|}
 & C^{A\times B}\\
\hline C^{A} & \pi_{1}^{\downarrow C}\\
C^{B} & \pi_{2}^{\downarrow C}
\end{array}\quad.
\]
\vspace{-0.85\baselineskip}

To show that it is not possible to implement a function $g$ with
the inverse type signature,
\[
g:\forall(A,B).\,C^{A\times B}\rightarrow C^{A}+C^{B}\quad,
\]
we choose the contrafunctor $C^{A}\triangleq A\rightarrow R$, where
$R$ is a fixed type. The type signature becomes
\[
g:\forall(A,B).\,(A\times B\rightarrow R)\rightarrow(A\rightarrow R)+(B\rightarrow R)\quad.
\]
To implement this function, we need to decide whether to return values
of type $A\rightarrow R$ or $B\rightarrow R$. Can we compute a value
of type $A\rightarrow R$ given a value of type $A\times B\rightarrow R$?
\[
g^{:(A\times B\rightarrow R)\rightarrow A\rightarrow R}\triangleq q^{:A\times B\rightarrow R}\rightarrow a^{:A}\rightarrow\text{???}^{:R}
\]
We cannot compute a value of type $R$ because that requires us to
apply the function $q$ to a pair $A\times B$, while we only have
a value of type $A$. So, the typed hole $\text{???}^{:R}$ cannot
be filled. 

Similarly, we are not able to compute a value of type $B\rightarrow R$
from a value of type $A\times B\rightarrow R$. Whatever choice we
make, $A\rightarrow R$ or $B\rightarrow R$, we cannot implement
the required type signature.

\textbf{(b)} We need to implement a function with type signature
\[
\forall(A,B).\,F^{A\times B}\rightarrow F^{A}\times F^{B}\quad.
\]
The types $A\times B$, $A$, and $B$ are related by the functions
$\pi_{1}:A\times B\rightarrow A$ and $\pi_{2}:A\times B\rightarrow B$.
Lifting these functions to the functor $F$, we obtain $\pi_{1}^{\uparrow F}:F^{A\times B}\rightarrow F^{A}$
and $\pi_{2}^{\uparrow F}:F^{A\times B}\rightarrow F^{B}$. It remains
to take the product of the resulting values:
\[
f^{:F^{A\times B}\rightarrow F^{A}\times F^{B}}\triangleq p^{:F^{A\times B}}\rightarrow(p\triangleright\pi_{1}^{\uparrow F})\times(p\triangleright\pi_{2}^{\uparrow F})\quad.
\]
\begin{lstlisting}
def f[F[_]: Functor, A, B](p: F[(A, B)]): (F[A], F[B]) =
  (p.map { case (a, b) => a }, p.map { case (a, b) => b })  // Or (p.map(_._1), p.map(_._2))
\end{lstlisting}
A shorter code for $f$ via the \textsf{``}diagonal\textsf{''} function $\Delta\triangleq(q^{:Q}\rightarrow q\times q)$
and the pair product $\boxtimes$ is
\[
f^{:F^{A\times B}\rightarrow F^{A}\times F^{B}}\triangleq\Delta\bef(\pi_{1}^{\uparrow F}\boxtimes\pi_{2}^{\uparrow F})\quad.
\]
This notation is sometimes easier to reason about when deriving properties
of functions.

If we try implementing a function $g$ with the inverse type signature,
\begin{equation}
g:\forall(A,B).\,F^{A}\times F^{B}\rightarrow F^{A\times B}\quad,\label{eq:type-signature-of-g-zip}
\end{equation}
we will find that $g$ \emph{can} be implemented for functors such
as $F^{A}\triangleq A\times A$, $F^{A}\triangleq\bbnum 1+A$, and
$F^{A}\triangleq P\rightarrow A$. It is not obvious how to find a
functor $F$ for which the function $g$ has no implementation. By
looking through the known functor constructions (Table~\ref{tab:f-Functor-constructions})
and trying various combinations, we eventually find a suitable functor:
$F^{A}\triangleq(P\rightarrow A)+(Q\rightarrow A)$. The type signature
of $g$ becomes
\[
g:\forall(A,B).\,\left((P\rightarrow A)+(Q\rightarrow A)\right)\times\left((P\rightarrow B)+(Q\rightarrow B)\right)\rightarrow(P\rightarrow A\times B)+(Q\rightarrow A\times B)\quad.
\]
The argument of this function is of type
\[
\left((P\rightarrow A)+(Q\rightarrow A)\right)\times\left((P\rightarrow B)+(Q\rightarrow B)\right)\quad,
\]
which can be transformed equivalently into a disjunction of four cases,
\[
(P\rightarrow A)\times(P\rightarrow B)+(P\rightarrow A)\times(Q\rightarrow B)+(Q\rightarrow A)\times(P\rightarrow B)+(Q\rightarrow A)\times(Q\rightarrow B)\quad.
\]
Implementing the function $g$ requires, in particular, to handle
the case when we are given values of types $P\rightarrow A$ and $Q\rightarrow B$,
and we are required to produce a value of type $(P\rightarrow A\times B)+(Q\rightarrow A\times B)$.
The resulting type signature
\[
(P\rightarrow A)\times(Q\rightarrow B)\rightarrow(P\rightarrow A\times B)+(Q\rightarrow A\times B)
\]
cannot be implemented: If we choose to return a value of type $P\rightarrow A\times B$,
we would need to produce a pair of type $A\times B$ from a value
of type $P$. However, producing a pair $A\times B$ requires, in
this case, to have values of \emph{both} types $P$ and $Q$, since
the given arguments have types $P\rightarrow A$ and $Q\rightarrow B$.
Similarly, we cannot return a value of type $Q\rightarrow A\times B$.

We find that the function $g$ cannot be implemented for the functor
$F^{A}\triangleq(P\rightarrow A)+(Q\rightarrow A)$. Functors $F$
for which the type signature~(\ref{eq:type-signature-of-g-zip})
\emph{can} be implemented are called \textsf{``}applicative\index{applicative functors}\textsf{''}
(see Chapter~\ref{chap:8-Applicative-functors,-contrafunc} for precise
conditions). The functor $F$ is an example of a functor that is not
applicative.

\subsubsection{Example \label{subsec:tc-Example-pointed-alternative}\ref{subsec:tc-Example-pointed-alternative}{*}}

(R.~O'Connor\index{Russell O'Connor} \footnote{This example is based on the post \texttt{\href{https://mail.haskell.org/pipermail/haskell-cafe/2015-November/122357.html}{https://mail.haskell.org/pipermail/haskell-cafe/2015-November/122357.html}}})
Assume that a functor $F$ admits a function $p$ with type signature

\begin{wrapfigure}{l}{0.63\columnwidth}%
\vspace{-0.75\baselineskip}
\begin{lstlisting}
def p[A, B, F[_]: Functor]: Either[A, F[B]] => F[Either[A, B]]
\end{lstlisting}

\vspace{-0.6\baselineskip}
\end{wrapfigure}%

\noindent ~\vspace{-0.5\baselineskip}
\[
p^{A,B}:A+F^{B}\rightarrow F^{A+B}\quad,
\]
additionally satisfying the special laws of identity and associativity,
\[
p^{\bbnum 0,B}=(b^{:B}\rightarrow\bbnum 0+b)^{\uparrow F}\quad,\quad\quad p^{A+B,C}=\,\begin{array}{|c||cc|}
 & A & F^{B+C}\\
\hline A & \text{id} & \bbnum 0\\
B+F^{C} & \bbnum 0 & p^{B,C}
\end{array}\,\bef p^{A,B+C}\quad.
\]
Show that the functor $F$ is pointed if such a function $p$ exists.
Conversely, show that any pointed functor $F$ admits a function $p$
with these properties.

\subparagraph{Solution}

To show that $F$ is pointed, it is sufficient to find a value $\text{wu}_{F}$
of type $F^{\bbnum 1}$. We note that the given function $p$ can
create values of type $F^{A+B}$ from input values of type $A+\bbnum 0$.
So, we set the type parameters $A=\bbnum 1$ and $B=\bbnum 0$ and
apply $p$ to the value $1+\bbnum 0^{:F^{\bbnum 0}}$,
\[
\text{wu}_{F}\triangleq(1+\bbnum 0^{:F^{\bbnum 0}})\triangleright p^{\bbnum 1,\bbnum 0}\triangleright(1+\bbnum 0\rightarrow1)^{\uparrow F}\quad.
\]
\begin{lstlisting}
val wu[F[_]: Functor]: F[Unit] = p[Unit, Nothing](Left(())).map { case Left(_) => () }
\end{lstlisting}

Conversely, assuming that $F$ is pointed, we use its $\text{pu}_{F}$
function to define $p$ as

\begin{wrapfigure}{l}{0.58\columnwidth}%
\vspace{-0.2\baselineskip}
\begin{lstlisting}
def p[F[_]: Functor : Pointed, A, B]
              : Either[A, F[B]] => F[Either[A, B]] = {
  case Left(a)     => pure[F, Either[A, B]](Left(a))
  case Right(fb)   => fb.map { b => Right[A, B](b) }
}
\end{lstlisting}

\vspace{-4\baselineskip}
\end{wrapfigure}%

\noindent \vspace{-0.75\baselineskip}
\[
p^{A,B}\triangleq\,\begin{array}{|c||c|}
 & F^{A+B}\\
\hline A & (a^{:A}\rightarrow a+\bbnum 0^{:B})\bef\text{pu}_{F}\\
F^{B} & (b^{:B}\rightarrow\bbnum 0^{:A}+b)^{\uparrow F}
\end{array}\quad.
\]

It remains to show that $p$ satisfies the required laws. The identity
law holds because
\begin{align*}
{\color{greenunder}\text{expect to equal }(b^{:B}\rightarrow\bbnum 0+b)^{\uparrow F}:}\quad & p^{\bbnum 0,B}=\,\begin{array}{|c||c|}
 & F^{\bbnum 0+B}\\
\hline \bbnum 0 & \text{(we may delete this line)}\\
F^{B} & (b^{:B}\rightarrow\bbnum 0+b)^{\uparrow F}
\end{array}\,=(b^{:B}\rightarrow\bbnum 0+b)^{\uparrow F}\quad.
\end{align*}
To verify the associativity law, we begin with its right-hand side
since it is more complicated:
\begin{align*}
 & \begin{array}{|c||cc|}
 & A & F^{B+C}\\
\hline A & \text{id} & \bbnum 0\\
B+F^{C} & \bbnum 0 & p^{B,C}
\end{array}\,\bef p^{A,B+C}=\,\begin{array}{|c||cc|}
 & A & F^{B+C}\\
\hline A & \text{id} & \bbnum 0\\
B+F^{C} & \bbnum 0 & p^{B,C}
\end{array}\,\bef\,\begin{array}{|c||c|}
 & F^{A+B+C}\\
\hline A & (a^{:A}\rightarrow a+\bbnum 0^{:B+C})\bef\text{pu}_{F}\\
F^{B+C} & (x^{:B+C}\rightarrow\bbnum 0^{:A}+x)^{\uparrow F}
\end{array}\\
 & =\,\begin{array}{|c||c|}
 & F^{A+B+C}\\
\hline A & (a^{:A}\rightarrow a+\bbnum 0^{:B+C})\bef\text{pu}_{F}\\
B+F^{C} & p^{B,C}\bef(x^{:B+C}\rightarrow\bbnum 0^{:A}+x)^{\uparrow F}
\end{array}\,=\,\begin{array}{|c||c|}
 & F^{A+B+C}\\
\hline A & (a^{:A}\rightarrow a+\bbnum 0^{:B+C})\bef\text{pu}_{F}\\
B & (b^{:B}\rightarrow b+\bbnum 0^{:C})\bef\text{pu}_{F}\bef(x^{:B+C}\rightarrow\bbnum 0^{:A}+x)^{\uparrow F}\\
F^{C} & (c^{:C}\rightarrow\bbnum 0^{:A+B}+c)^{\uparrow F}
\end{array}\quad.
\end{align*}
In the last line, we have expanded the type matrix to three rows corresponding
to the disjunctive type $A+B+F^{C}$. We need to show that the last
matrix equals $p^{A+B,C}$; so let us rewrite $p^{A+B,C}$ as a similarly
expanded type matrix, using the type isomorphisms such as $\bbnum 0^{:A}+\bbnum 0^{:B}\cong\bbnum 0^{:A+B}$:
\[
p^{A+B,C}=\,\begin{array}{|c||c|}
 & F^{A+B+C}\\
\hline A & (a^{:A}\rightarrow a+\gunderline{\bbnum 0^{:B}+\bbnum 0^{:C}})\bef\text{pu}_{F}\\
B & (b^{:B}\rightarrow\bbnum 0^{:A}+b+\bbnum 0^{:C})\bef\text{pu}_{F}\\
F^{C} & (c^{:C}\rightarrow\gunderline{\bbnum 0^{:A}+\bbnum 0^{:B}}+c)^{\uparrow F}
\end{array}\,=\,\begin{array}{|c||c|}
 & F^{A+B+C}\\
\hline A & (a^{:A}\rightarrow a+\bbnum 0^{:B+C})\bef\text{pu}_{F}\\
B & (b^{:B}\rightarrow\bbnum 0^{:A}+b+\bbnum 0^{:C})\bef\text{pu}_{F}\\
F^{C} & (c^{:C}\rightarrow\bbnum 0^{:A+B}+c)^{\uparrow F}
\end{array}\quad.
\]
The only remaining difference is in the second lines of the matrices.
We write those lines separately: 
\begin{align*}
{\color{greenunder}\text{expect to equal }(b^{:B}\rightarrow\bbnum 0^{:A}+b+\bbnum 0^{:C})\bef\text{pu}_{F}:}\quad & (b^{:B}\rightarrow b+\bbnum 0^{:C})\bef\gunderline{\text{pu}_{F}\bef(x^{:B+C}\rightarrow\bbnum 0^{:A}+x)^{\uparrow F}}\\
{\color{greenunder}\text{naturality law of }\text{pu}_{F}:}\quad & =\gunderline{(b^{:B}\rightarrow b+\bbnum 0^{:C})\bef(x^{:B+C}\rightarrow\bbnum 0^{:A}+x)}\bef\text{pu}_{F}\\
{\color{greenunder}\text{compute function composition}:}\quad & =(b^{:B}\rightarrow\bbnum 0^{:A}+b+\bbnum 0^{:C})\bef\text{pu}_{F}\quad.
\end{align*}
This completes the proof of the required laws.

\subsection{Exercises\index{exercises}}

\subsubsection{Exercise \label{subsec:tc-Exercise-1}\ref{subsec:tc-Exercise-1}}

Define a PTVF \lstinline!def isLong[T]: Boolean! that returns \lstinline!true!
for \lstinline!T = Long! or \lstinline!Double! and returns \lstinline!false!
for \lstinline!T = Int!, \lstinline!Short!, or \lstinline!Float!.
The function should remain undefined for other types \lstinline!T!.

\subsubsection{Exercise \label{subsec:tc-Exercise-2}\ref{subsec:tc-Exercise-2}}

Implement a \lstinline!Monoid! instance for the type $\text{String}\times(\bbnum 1+\text{Int})$.

\subsubsection{Exercise \label{subsec:tc-Exercise-3}\ref{subsec:tc-Exercise-3}}

\textbf{(a)} If $A$ is a monoid and $R$ any type, implement a \lstinline!Monoid!
instance for $R\rightarrow A$:
\begin{lstlisting}
def monoidFunc[A: Monoid, R]: Monoid[R => A] = ???
\end{lstlisting}
Prove that the monoid laws hold for that instance.

\textbf{(b)} With the choice \lstinline!R = Boolean!, use the type
equivalence $(R\rightarrow A)=(\bbnum 2\rightarrow A)\cong A\times A$
and verify that the monoid instance \lstinline!monoidFunc[A, Boolean]!
is the same as the monoid instance for $A\times A$ computed by \lstinline!monoidPair[A, A]!
in Section~\ref{subsec:Monoids-constructions}.

\subsubsection{Exercise \label{subsec:tc-Exercise-4}\ref{subsec:tc-Exercise-4}}

Show that if \lstinline!S! is a semigroup then \lstinline!Option[S]!
and \lstinline!Option[(S, S)]! are monoids.

\subsubsection{Exercise \label{subsec:Exercise-1-monads-1}\ref{subsec:Exercise-1-monads-1}}

A framework implements a \textsf{``}route\textsf{''} type $R$ as $R\triangleq Q\rightarrow(E+S)$,
where $Q$ is a query, $E$ is an error response, and $S$ is a success
response. A server is defined as a combination of several routes.
For a given query $Q$, the response is the first route (if it exists)
that yields a success response. Implement the route combination operation
and show that it makes $R$ into a semigroup. What would be necessary
to make $R$ into a monoid?

\subsubsection{Exercise \label{subsec:tc-Exercise-5}\ref{subsec:tc-Exercise-5}}

Using the \texttt{cats} library, implement a \lstinline!Functor!
instance for \lstinline!type F[T] = Try[Seq[T]]!.

\subsubsection{Exercise \label{subsec:tc-Exercise-6}\ref{subsec:tc-Exercise-6}}

Using the \texttt{cats} library, implement a \lstinline!Bifunctor!
instance for $B^{X,Y}\triangleq\left(\text{Int}\rightarrow X\right)+Y\times Y$.

\subsubsection{Exercise \label{subsec:tc-Exercise-7}\ref{subsec:tc-Exercise-7}}

Define a \lstinline!Profunctor! typeclass having the method \lstinline!xmap!:

\begin{lstlisting}
def xmap[A, B](f: A => B, g: B => A): F[A] => F[B]
\end{lstlisting}
Implement a \lstinline!Profunctor! instance for $P^{A}\triangleq A\rightarrow\left(\text{Int}\times A\right)$.

\subsubsection{Exercise \label{subsec:tc-Exercise-8}\ref{subsec:tc-Exercise-8}}

Implement a \lstinline!Functor! instance for the recursive type $Q^{A}\triangleq\text{String}+A\times A\times Q^{A}$.

\subsubsection{Exercise \label{subsec:tc-Exercise-8-1}\ref{subsec:tc-Exercise-8-1}}

Show explicitly that a value $\text{wu}_{C}:C^{\bbnum 1}$ is computationally
equivalent to a value $\text{pu}_{C}:\forall A.\,C^{A}$ that satisfies
the naturality law~(\ref{eq:naturality-law-for-pure-for-contrafunctors}).

\subsubsection{Exercise \label{subsec:tc-Exercise-9}\ref{subsec:tc-Exercise-9}}

Using a function parameterized by the type constructors $F$ and $G$
(required to be functors), implement a \lstinline!Functor! instance
for $F^{A}\times G^{A}$. 

\subsubsection{Exercise \label{subsec:tc-Exercise-10}\ref{subsec:tc-Exercise-10}}

Implement a \lstinline!Functor! instance for $F^{A}\rightarrow G^{A}$
as a function parameterized by type constructors $F$ and $G$, where
$F^{A}$ is required to be a contrafunctor and $G^{A}$ is required
to be a functor. For the contrafunctor $F$, use either the \lstinline!Contrafunctor!
typeclass from Example~\ref{subsec:tc-Example-6} or the \texttt{cats}
library\textsf{'}s typeclass \lstinline!Contravariant!.

\subsubsection{Exercise \label{subsec:tc-Exercise-9-1}\ref{subsec:tc-Exercise-9-1}{*}}

\textbf{(a)} Implement a function with type signature $F^{A}+F^{B}\rightarrow F^{A+B}$
parameterized by a type constructor $F$ (required to be a functor)
and by arbitrary types $A$, $B$. Show that the inverse type signature
$F^{A+B}\rightarrow F^{A}+F^{B}$ is not implementable for some functors
$F$. 

\textbf{(b)} Implement a function with type signature $C^{A+B}\rightarrow C^{A}\times C^{B}$
parameterized by a type constructor $C$ (required to be a contrafunctor)
and by arbitrary types $A$, $B$. Show that the inverse type signature
$C^{A}\times C^{B}\rightarrow C^{A+B}$ is not implementable for some
contrafunctors $C$.

\subsubsection{Exercise \label{subsec:tc-Exercise-9-1-1}\ref{subsec:tc-Exercise-9-1-1}{*}}

Implement a function with type signature $F^{A\rightarrow B}\rightarrow A\rightarrow F^{B}$
parameterized by a functor $F$ and arbitrary types $A$, $B$. Show
that the inverse type signature, $(A\rightarrow F^{B})\rightarrow F^{A\rightarrow B}$,
cannot be implemented for some functors $F$. (Functors admitting
a function with that type signature are called \textsf{``}rigid\textsf{''}; see Section~\ref{subsec:Rigid-functors}.)

\subsubsection{Exercise \label{subsec:tc-Exercise-9-1-1-1}\ref{subsec:tc-Exercise-9-1-1-1}{*}}

(dual O'Connor\index{Russell O'Connor}) Assume that a functor $F$
admits a function $q$ with type signature

\begin{wrapfigure}{l}{0.52\columnwidth}%
\vspace{-0.75\baselineskip}
\begin{lstlisting}
def q[A, B, F[_]: Functor]: F[(A, B)] => (A, F[B])
\end{lstlisting}

\vspace{-1.6\baselineskip}
\end{wrapfigure}%

\noindent $q^{A,B}:F^{A\times B}\rightarrow A\times F^{B}$, additionally
satisfying the special laws of identity and associativity:
\[
q^{\bbnum 1,B}=f^{:F^{\bbnum 1\times B}}\rightarrow1\times(f\triangleright(1\times b^{:B}\rightarrow b)^{\uparrow F})\quad,\quad\quad q^{A,B\times C}\bef(\text{id}^{A}\boxtimes q^{B,C})=q^{A\times B,C}\quad.
\]
This Scala code illustrates the required laws in full detail:
\begin{lstlisting}
      // For any value f: F[(Unit, B)], we first compute
val (a1, b1) = q[Unit, B, F](f)._1
      // Then we must have:    a1 == ()   and   b1 == f.map { case (_, b) => b }

      // For any value p: F[(A, B, C)], we first compute
val ((a1: A, b1: B), f1: F[C]) = q[(A, B), C, F](p.map { case (a, b, c) => ((a, b), c) })
val (a2: A, f2: F[(B, C)]) = q[A, (B, C), F](p.map { case (a, b, c) => (a, (b, c)) }
      // Then we must have:    a1 == a2   and   (b1, f1) == p[B, C, F](f2)
\end{lstlisting}
The following naturality law should also hold for $q$,
\[
(f^{:A\rightarrow C}\boxtimes g^{:B\rightarrow D})^{\uparrow F}\bef q^{C,D}=q^{A,B}\bef f\boxtimes(g^{\uparrow F})\quad.
\]
\begin{lstlisting}
      // For any value k: F[(A, B)] and any functions f: A => C, g: B => D, first compute
val (a: A, fb: F[B]) = q[A, B, F](k)  // Then we must have:
(f(a), fb.map(g)) == q[C, D, F](k.map { case (a, b) => (f(a), g(b)) })
\end{lstlisting}
Show that the functor $F$ is co-pointed if a function $q$ with these
properties exists. Conversely, show that any lawful co-pointed functor
$F$ admits a function $q$ with these properties.

\section{Further developments}

\subsection{The existence of values for recursive types\label{subsec:Recursive-types-and-the-existence-of-their-values}}

A recursive type $T$ is defined by a type equation such as $T\triangleq\bbnum 1+\text{Int}+T\times T$.
Can we decide whether such a type equation has a \textsf{``}solution\textsf{''}, i.e.,
a well-defined type $T$ with values that we can create and manipulate
in a program?

In all examples seen so far, the recursive type equations\index{recursive type equation}
had the form $T\triangleq S^{T}$ where the type constructor $S$
is a \emph{functor}. Type equations with non-functor $S$ (e.g., the
equation $T\triangleq T\rightarrow\text{Int}$) do not seem to be
useful in practice, and we will not consider them in this book.

In a rigorous approach, showing that $T$ is a \textsf{``}solution\textsf{''} (called
a \textbf{fixpoint}\index{fixpoint type}) of the type equation $T\triangleq S^{T}$
means proving that the types $T$ and $S^{T}$ are equivalent (isomorphic).
We must implement this type isomorphism as two functions, named e.g.,
\lstinline!fix! and \lstinline!unfix!, satisfying the conditions
\[
\text{fix}:S^{T}\rightarrow T\quad,\quad\quad\text{unfix}:T\rightarrow S^{T}\quad,\quad\quad\text{fix}\bef\text{unfix}=\text{id}\quad,\quad\quad\text{unfix}\bef\text{fix}=\text{id}\quad.
\]

Given a type constructor $S$, we can define the recursive type $T$
with this Scala code,
\begin{lstlisting}
final case class T(s: S[T])               // Type constructor S[_] must be already defined.
def fix:    S[T] => T   =   { s => T(s) }
def unfix:  T => S[T]   =   { t => t.s }
\end{lstlisting}
We can generalize this code to a \textsf{``}fixpoint\textsf{''} constructor $\text{Fix}^{S}$
that is \emph{parameterized} by $S$:
\begin{lstlisting}
final case class Fix[S[_]](s: S[Fix[S]])
def fix[S[_]]:    S[Fix[S]] => Fix[S]   =   { s => Fix(s) }
def unfix[S[_]]:  Fix[S] => S[Fix[S]]   =   { t => t.s }
\end{lstlisting}

In both implementations, the functions \lstinline!fix! and \lstinline!unfix!
are inverses of each other because they merely wrap and unwrap values
within a case class. So, we are always able to write code that \emph{defines}
the recursive type $T$. The remaining question is whether we will
be able to create values of type $T$.

Applying structural analysis to the functor $S$, we begin with the
constant functor $S^{A}\triangleq Z$, where $Z$ is a fixed type.
The type equation $T\triangleq S^{T}$ is just $T\triangleq Z$; so
$T$ is not a recursive type.

The next case is the identity functor $S^{A}\triangleq A$. The type
equation $T\triangleq S^{T}$ has the form $T\triangleq T$; since
all types $T$ satisfy that equation trivially, we find that the identity
functor does not define any specific type $T$. If we translate this
type equation into Scala code, we will run into a problem with recursion:

\begin{wrapfigure}{l}{0.46\columnwidth}%
\vspace{-1\baselineskip}
\begin{lstlisting}
type Id[A] = A
final case class T(s: Id[T])
// Equivalent to `final case class T(s: T)`.
val x = T(x)               // Infinite loop!
\end{lstlisting}

\vspace{-1.15\baselineskip}
\end{wrapfigure}%

\noindent A value of \lstinline!case class T! can be created only
if we supply a value of type \lstinline!T!. Writing \lstinline!def x: T = T(x)!
instead of \lstinline!val! does not help: the evaluation of the code
for \lstinline!x! will not terminate. It is clear that this recursive
definition is invalid: we are unable to create values of the resulting
type \lstinline!T!, i.e., the type \lstinline!T! is void.\index{infinite loop in type recursion}

Next, consider a product functor such as $S^{A}\triangleq A\times A\times\text{Int}$.
Can we create values of type $T\triangleq S^{T}$?

\begin{wrapfigure}{l}{0.46\columnwidth}%
\vspace{-0.8\baselineskip}
\begin{lstlisting}
final case class T(s: (T, T, Int))
val x = T(s = (x, x, 123))  // Infinite loop!
\end{lstlisting}

\vspace{-1\baselineskip}
\end{wrapfigure}%

\noindent We again have an infinite loop when creating values of type
\lstinline!T!. As in the example with the identity functor, the case
class \lstinline!T! requires us to compute some values of type \lstinline!T!
before we can create a value of type \lstinline!T!. That requirement
is impossible to satisfy.

A disjunctive type, e.g., $S^{A}\triangleq\text{Int}+A\times A$,
allows us to create values of type $\text{Fix}^{S}$ with no difficulty:

\begin{wrapfigure}{l}{0.46\columnwidth}%
\vspace{-0.75\baselineskip}
\begin{lstlisting}
final case class T(s: Either[Int, (T, T)])
val x: T = T(Left(123))     // OK
val y: T = T(Right(x, x))   // OK
\end{lstlisting}

\vspace{-1\baselineskip}
\end{wrapfigure}%

\noindent We are able to create \lstinline!x! of type $\text{Int}+\bbnum 0^{:T\times T}$
without need for any previous values of $T$. We can then use \lstinline!x!
to create a value \lstinline!y! of type $T$. This resembles defining
a value by induction: the base case is the type $\text{Int}+\bbnum 0^{:T\times T}$,
which is a disjunctive part of $S^{A}$ that does \emph{not} contain
any values of type $A$. The inductive step is the type $\bbnum 0^{:\text{Int}}+T\times T$,
which creates a new value of type $T$ from two previous values. Type
recursion terminates when the base case exists.

The examples we saw previously, $S^{A}\triangleq A$ and $S^{A}\triangleq\text{Int}\times A\times A$,
do not have a base case where a value of type $S^{A}$ could be computed
without need for any previous values of type $A$. 

Given a functor $S^{A}$, how can we determine whether the type recursion
$T\triangleq S^{T}$ terminates? If $S^{A}$ is a \emph{polynomial}
functor, we can view $S^{A}$ as a polynomial function of $A$ and
reduce it to the form 
\begin{equation}
S^{A}\cong C_{0}+C_{1}\times A+C_{2}\times A\times A+...\label{eq:functor-polynomial-normal-form}
\end{equation}
It is clear from this formula that the type $C_{0}$ is found by setting
$A=\bbnum 0$ in $S^{A}$, i.e., $C_{0}\cong S^{\bbnum 0}$. If we
can compute a value $c_{0}$ of type $C_{0}$ (i.e., if $C_{0}$ is
not void, $C_{0}\not\cong\bbnum 0$), a base-case value $t_{0}$ of
type $T$ is found as
\[
t_{0}^{:T}\triangleq c_{0}^{:C_{0}}+\bbnum 0^{:C_{1}\times A}+\bbnum 0^{:C_{2}\times A\times A}+...
\]
Further values of type $T$ could be computed as $c_{1}\times t_{0}$
or $c_{2}\times t_{0}\times t_{0}$, etc.

We conclude that the recursive type $T\triangleq S^{T}$ defined via
a \emph{polynomial} functor $S$ will be non-void (i.e., type recursion
will terminate) when the type $S^{\bbnum 0}$ is non-void.

In the examples $S^{A}\triangleq A$ and $S^{A}\triangleq\text{Int}\times A\times A$,
we find $S^{\bbnum 0}\cong\bbnum 0$, so type recursion is invalid.

It remains to consider functors $S$ that cannot be reduced to the
polynomial form~(\ref{eq:functor-polynomial-normal-form}). As an
example, take $S^{A}\triangleq\text{String}\times(\text{Int}\rightarrow A)$.
For this functor $S$, the condition $S^{\bbnum 0}\not\cong\bbnum 0$
does not hold:
\begin{align*}
 & S^{\bbnum 0}\cong\text{String}\times(\gunderline{\text{Int}\rightarrow\bbnum 0})\\
{\color{greenunder}\text{use the type equivalence }\left(\text{Int}\rightarrow\bbnum 0\right)\cong\bbnum 0:}\quad & \quad\cong\text{String}\times\bbnum 0\cong\bbnum 0\quad.
\end{align*}
Nevertheless, we can write Scala code implementing values of the type
$T$ defined by $T\triangleq S^{T}$:
\begin{lstlisting}
final case class T(message: String, next: Int => T)
val t: T = T("start", n => T(s"have $n", _ => t))   // A recursive `val`.
\end{lstlisting}
The value \lstinline!t! refers to itself recursively within a nested
function \lstinline!_ => t!, and there is no \textsf{``}base case\textsf{''} in the
type $S^{T}$. However, the recursion does not lead to an infinite
loop; we can use \lstinline!t! safely:
\begin{lstlisting}
scala> t.next(10)
res0: T = T(have 10,<function1>)

scala> t.next(10).next(10)
res1: T = T(start,<function1>)
\end{lstlisting}
A value of type $T$ contains a function \lstinline!next! that, when
applied, returns a new value of the same type $T$. The new value
of type $T$ does not need to be computed in advance: its evaluation
is \emph{delayed} until some code decides to call \lstinline!next!.
For this reason, an infinite loop is avoided even though the structure
functor $S$ has no \textsf{``}base case\textsf{''}. Values of type $T$ can be viewed
as an infinite stream of \lstinline!String! values computed on demand.
An \lstinline!Int! value is required in order to produce the next
element of the stream. A symbolic (and non-rigorous) representation
of that type is
\[
T=\text{String}\times(\text{Int}\rightarrow\text{String}\times(\text{Int}\rightarrow\text{String}\times(\text{Int}\rightarrow\text{String}\times...)))\quad.
\]

As another example, consider $S^{A}\triangleq\bbnum 1\rightarrow\text{String}+\text{Int}\times A$.
Using the type equivalence $P\cong(\bbnum 1\rightarrow P)$, we could
transform $S^{A}$ into an equivalent functor $\tilde{S}^{A}$ in
the polynomial form~(\ref{eq:functor-polynomial-normal-form}),
\[
\tilde{S}^{A}\triangleq\text{String}+\text{Int}\times A\quad.
\]
Although the types $S^{A}$ and $\tilde{S}^{A}$ are equivalent, the
recursive types $\text{Fix}^{S}$ and $\text{Fix}^{\tilde{S}}$ are
different. While 
\begin{align*}
\text{Fix}^{\tilde{S}} & =\text{String}+\text{Int}\times(\text{String}+\text{Int}\times(\text{String}+\text{Int}\times...))\\
 & \cong\left(\bbnum 1+\text{Int}+\text{Int}\times\text{Int}+\text{Int}\times\text{Int}\times\text{Int}+...\right)\times\text{String}\cong\text{String}\times\text{List}^{\text{Int}}\quad,
\end{align*}
the type $\text{Fix}^{S}$ admits recursively defined values representing
\emph{unbounded} streams of integers, e.g.
\begin{lstlisting}[mathescape=true]
final case class T(e: () => Either[String, (Int, T)]) // Define the type $\color{dkgreen} T \triangleq\text{String}+\text{Int}\times T$.
val t1: T = T(() => Right((1, t1)))                   // Stream [1, 1, 1, ...].
def t2(n: Int): T = T(() => Right((n, t2(n+1))))      // Stream [n, n+1, n+2, ...].
\end{lstlisting}
The type $T\triangleq\text{Fix}^{S}$ also admits finite streams that
may be defined as \emph{non-recursive} values of type $T$:
\begin{lstlisting}
val t0 = T(() => Right((10, T(() => Left("stop")))))  // Finite stream [10, "stop"].
\end{lstlisting}
We can recognize that $\text{Fix}^{S}$ has non-recursive values by
checking that the type $S^{\bbnum 0}$ is not void:
\[
S^{\bbnum 0}=\bbnum 1\rightarrow\text{Int}\times\bbnum 0+\text{String}\cong\bbnum 1\rightarrow\text{String}\cong\text{String}\not\cong\bbnum 0\quad.
\]

How can we recognize functors $S$ that admit valid recursive values
of type $\text{Fix}^{S}$? The exponential functor construction (Statement~\ref{subsec:functor-Statement-functor-exponential})
shows that $C^{A}\rightarrow P^{A}$ is a functor when $C$ is a contrafunctor
and $P$ is a functor. If the type expression for $S^{A}$ contains
a sub-expression of the form $C^{A}\rightarrow P^{A}$, how can we
implement a value of type $C^{T}\rightarrow P^{T}$? We can use recursion
to implement a value of $T$, as long as we can then somehow produce
a value of type $P^{T}$ out of a value of type $T$. This is precisely
the condition for $P^{\bullet}$ to be a pointed functor. The contrafunctor
$C^{A}$ is an argument of the function of type $C^{A}\rightarrow P^{A}$,
so we are not required to produce values of type $C^{A}$\textemdash{}
we \emph{consume} those values. It follows that we can implement a
value of type $C^{T}\rightarrow P^{T}$ (with $T=\text{Fix}^{S}$)
as long as $P^{\bullet}$ is a pointed functor. As we saw in Section~\ref{subsec:Pointed-functors:-motivation},
a functor $P^{\bullet}$ is pointed if we can compute a value of type
$P^{\bbnum 1}$.

In the example $S^{A}\triangleq\text{String}\times(\text{Int}\rightarrow A)$,
the functor $S^{A}$ is pointed since 
\[
S^{\bbnum 1}\cong\text{String}\times(\text{Int}\rightarrow\bbnum 1)\cong\text{String}\not\cong\bbnum 0\quad.
\]

This consideration applies to any sub-expression of the form $C^{A}\rightarrow P^{A}$
within the type constructor $S^{A}$. The condition for values of
$\text{Fix}^{S}$ to exist is that every functor $P^{A}$ involved
in such sub-expressions should be pointed. To check that, we can set
the type parameter $A=\bbnum 1$ in all return types of \emph{functions}
within $S^{A}$. If the resulting type is not void, we will be able
to implement a recursively defined value of type $\text{Fix}^{S}$.

If the functor $S^{A}$ has the property $S^{\bbnum 0}\not\cong\bbnum 0$
(i.e., we have a base case for the inductive definition of $\text{Fix}^{S}$),
we will also be able to implement non-recursive values of type $\text{Fix}^{S}$.

We conclude that $S^{\bbnum 0}\not\cong\bbnum 0$ is a \emph{sufficient}
condition for the type $\text{Fix}^{S}$ to be non-void. If $S$ is
a polynomial functor, this condition is also a necessary condition.
For exponential-polynomial functors $S$, recursive values of type
$\text{Fix}^{S}$ can be implemented if every function-type sub-expression
$C^{A}\rightarrow P^{A}$ in $S^{A}$ involves a pointed functor $P$
(i.e., if $P^{\bbnum 1}\not\cong\bbnum 0$).

\subsection{Proofs of associativity of \texttt{concat} for lists and arrays\label{subsec:Proofs-for-associativity-law-lists-and-arrays-concat}}

The \lstinline!concat! function is defined for both lists and arrays,
and works similarly for these data types:
\begin{lstlisting}
scala> Array.concat(Array(1, 2), Array(3, 4), Array(5, 6))
res0: Array[Int] = Array(1, 2, 3, 4, 5, 6)

scala> List.concat(List(1, 2), List(3, 4), List(5, 6))
res1: List[Int] = List(1, 2, 3, 4, 5, 6)
\end{lstlisting}
In this section, we will show rigorously that concatenation is an
associative operation.

In Scala, \lstinline!Array[A]! is a sequence whose elements can be
accessed by index. The array access function (the \lstinline!apply!
method defined on the \lstinline!Array! class) is a partial function
of type \lstinline!Int => A! whose integer argument must be between
$0$ and $n-1$, where $n$ is the array length:
\begin{lstlisting}
val x = Array("a", "b", "c")

scala> x(2)  // The syntax `x(2)` is the same as `x.apply(2)`. 
res2: String = c

scala> x(3)  // Applying the partial function `x.apply` to the value 3 will fail:
java.lang.ArrayIndexOutOfBoundsException: 3
\end{lstlisting}
We can denote the type of this function by $\text{Int}_{[0,n-1]}\rightarrow A$
to indicate the bounds of the index.

The \lstinline!List! type constructor is a recursive disjunctive
type defined by the type equation
\[
\text{List}^{A}\triangleq\bbnum 1+A\times\text{List}^{A}=\bbnum 1+A+A\times A+A\times A\times A+...
\]
Although the definitions of types are different, lists and arrays
are conceptually similar \textemdash{} they are both sequences of
values of type $A$. However, proving properties is easier for non-recursive
types than for recursive types. We begin by proving the associativity
property of the array concatenation. 

\subsubsection{Statement \label{subsec:Statement-concat-array-associativity}\ref{subsec:Statement-concat-array-associativity}}

For arrays, $\text{Array}_{n}^{A}\triangleq\text{Int}_{[0,n-1]}\rightarrow A$,
the \lstinline!concat! function (denoted $\pplus$) defined by
\[
a_{1}^{:\text{Array}_{n_{1}}^{A}}\pplus a_{2}^{:\text{Array}_{n_{2}}^{A}}\triangleq i^{:\text{Int}_{[0,n_{1}+n_{2}-1]}}\rightarrow\begin{cases}
0\leq i<n_{1}: & a_{1}(i)\\
n_{1}\leq i<n_{1}+n_{2}: & a_{2}(i-n_{1})
\end{cases}
\]
satisfies the associativity law
\[
(a_{1}\pplus a_{2})\pplus a_{3}=a_{1}\pplus(a_{2}\pplus a_{3})\quad.
\]


\subparagraph{Proof}

Both sides of the law evaluate to the same partial function of type
$\text{Int}\rightarrow A$:
\[
(a_{1}\pplus a_{2})\pplus a_{3}=a_{1}\pplus(a_{2}\pplus a_{3})=i^{:\text{Int}_{[0,n_{1}+n_{2}+n_{3}-1]}}\rightarrow\begin{cases}
0\leq i<n_{1}: & a_{1}(i)\\
n_{1}\leq i<n_{1}+n_{2}: & a_{2}(i-n_{1})\\
n_{1}+n_{2}\leq i<n_{1}+n_{2}+n_{3}: & a_{3}(i-n_{1}-n_{2})
\end{cases}\quad.
\]

Now we establish a rigorous equivalence between the \lstinline!List!
and \lstinline!Array! types.

\subsubsection{Statement \label{subsec:Statement-array-list-equivalence}\ref{subsec:Statement-array-list-equivalence}}

The type $\text{List}^{A}\triangleq\bbnum 1+A\times\text{List}^{A}$
is equivalent to $\text{Array}_{n}^{A}\triangleq\text{Int}_{[0,n-1]}\rightarrow A$,
where $n\geq0$ and $\text{Int}_{[0,n-1]}$ is the (possibly empty)
subset of integers $i$ within the range $0\leq i\leq n-1$.

\subparagraph{Proof}

We need to implement two isomorphism maps $f_{1}$, $f_{2}$ and show
that 
\[
f_{1}:\text{Array}_{n}^{A}\rightarrow\text{List}^{A}\quad,\quad\quad f_{2}:\text{List}^{A}\rightarrow\text{Array}_{n}^{A}\quad,\quad\quad f_{1}\bef f_{2}=\text{id}\quad,\quad\quad f_{2}\bef f_{1}=\text{id}\quad.
\]

To implement $f_{1}$, we proceed by induction in $n$. The base case
is $n=0$, and we map $\text{Array}_{0}$ into an empty list. The
inductive step assumes that $f_{1}$ is already defined on arrays
of length $n$, and we now need to define $f_{1}$ for arrays of length
$n+1$. An array of length $n+1$ is a partial function $g^{:\text{Int}_{[0,n]}\rightarrow A}$
defined on the integer interval $[0,n]$. We now split that array
into its first element, $g(0)$, and the rest of the array, which
needs to be represented by another partial function, say $g'\triangleq i\rightarrow g(i+1)$,
defined on the integer interval $[0,n-1]$. The function $g$ represents
an array of length $n$. By the inductive assumption, $f_{1}$ is
already defined for arrays of length $n$. So, we can compute $f_{1}(g'):\text{List}^{A}$
and thus create a value of type $\bbnum 0+A\times\text{List}^{A}$,
which is equivalent to a value of type $\text{List}^{A}$.

\begin{wrapfigure}{l}{0.4\columnwidth}%
\vspace{-0.75\baselineskip}
\begin{lstlisting}
def f1[A](arr: Array[A]): List[A] =
  if (arr.length == 0) List()
  else arr(0) :: f1(arr.tail)
\end{lstlisting}

\vspace{-1.25\baselineskip}
\end{wrapfigure}%

\noindent \vspace{-1.25\baselineskip}
\begin{align*}
f_{1}(\text{Array}_{0}^{A}) & \triangleq\bbnum 1+\bbnum 0^{:A\times\text{List}^{A}}\quad,\\
f_{1}(g^{:\text{Int}_{[0,n]}\rightarrow A}) & \triangleq\bbnum 0+g(0)^{:A}\times\overline{f_{1}}(i\rightarrow g(i+1))\quad.
\end{align*}
\vspace{-0.5\baselineskip}

To implement $f_{2}$, we use induction in the structure of the list.
The length $n$ of the array is not known in advance and needs to
be computed as we perform pattern-matching on the given \lstinline!List[A]!
value. The base case is an empty list, which yields an empty array
(i.e., an array of length $n=0$). In the inductive step, we assume
that we already defined $f_{2}$ on lists of length $n$, and we now
need to define $f_{2}$ for lists of length $n+1$. Such a list must
have the form $\bbnum 0+x^{:A}\times s^{:\text{List}^{A}}$, where
$s$ is a list of length $n$. By the inductive assumption, we are
allowed to apply $f_{2}$ to $s$ and obtain an array of length $n$,
i.e., a partial function $g^{:\text{Int}_{[0,n-1]}\rightarrow A}$.
So we define $f_{2}(\bbnum 0+x\times s)$ as a new array whose $0^{\text{th}}$
element is $x$ and the $i^{\text{th}}$ element is computed by applying
the function $g\triangleq f_{2}(s)$ to $i-1$:

\begin{wrapfigure}{l}{0.4363\columnwidth}%
\vspace{-0.75\baselineskip}
\begin{lstlisting}
def f2[A: ClassTag]: List[A] => Array[A] =
{  case List()   => Array()
   case x :: s   => Array(x) ++ f2.apply(s)
}
\end{lstlisting}

\vspace{-1.25\baselineskip}
\end{wrapfigure}%

\noindent \vspace{-1.25\baselineskip}
\begin{align*}
f_{2}(\bbnum 1+\bbnum 0^{:A\times\text{List}^{A}}) & \triangleq\text{Array}_{0}^{A}\quad,\\
f_{2}(\bbnum 0+x^{:A}\times s^{:\text{List}^{A}}) & \triangleq i^{:\text{Int}_{[0,n]}}\rightarrow\begin{cases}
i=0: & x\quad,\\
i\geq1: & \overline{f_{2}}(s)(i-1)\quad.
\end{cases}
\end{align*}
\vspace{-0.5\baselineskip}

To show that $f_{1}$ and $f_{2}$ are inverse functions for each
other, we again need to use induction. The base case is the empty
list and the empty array, which are indeed mapped isomorphically to
each other. The inductive step for $f_{1}\bef f_{2}$ is an array
of length $n+1$ with the inductive assumption that $\overline{f_{1}\bef f_{2}}=\text{id}$
for arrays of length $n$. Writing out the code of $f_{1}\bef f_{2}$,
we find that $g\triangleright f_{1}\bef f_{2}=g$:
\begin{align*}
 & g^{:\text{Int}_{[0,n]}\rightarrow A}\triangleright f_{1}\bef f_{2}=g\triangleright f_{1}\triangleright f_{2}=(\bbnum 0+g(0)\times\overline{f_{1}}(i\rightarrow g(i+1)))\triangleright f_{2}\\
 & =i\rightarrow\begin{cases}
i=0: & g(0)\\
i\geq1: & \gunderline{\overline{f_{2}}(\overline{f_{1}}}(i\rightarrow g(i+1)))(i-1)
\end{cases}=i\rightarrow\begin{cases}
i=0: & g(0)\\
i\geq1: & \gunderline{\text{id}}(i\rightarrow g(i+1)))(i-1)
\end{cases}\\
 & =i\rightarrow\begin{cases}
i=0: & g(0)\\
i\geq1: & g(\gunderline{\left(i-1\right)+1})
\end{cases}=\left(i\rightarrow g(i)\right)=g.
\end{align*}
Similarly, we find that $(\bbnum 0+x^{:A}\times s^{:\text{List}^{A}})\triangleright f_{2}\bef f_{1}=(\bbnum 0+x^{:A}\times s^{:\text{List}^{A}})$
via this calculation:
\begin{align*}
 & (\bbnum 0+x^{:A}\times s^{:\text{List}^{A}})\triangleright f_{2}\bef f_{1}=f_{1}\left(i^{:\text{Int}_{[0,n]}}\rightarrow\begin{cases}
i=0: & x\\
i\geq1: & \overline{f_{2}}(s)(i-1)
\end{cases}\right)\\
 & =\bbnum 0+x\times\overline{f_{1}}(\gunderline{i\rightarrow\overline{f_{2}}(s)(i+1-1)})=\bbnum 0+x\times\gunderline{\overline{f_{1}}(\overline{f_{2}}}(s))=\bbnum 0+x\times s\quad.
\end{align*}
This concludes the proof of the isomorphism between \lstinline!Array!
and \lstinline!List!. 

Since arrays and lists are isomorphic as types, the concatenation
for lists is associative as long as we show that the concatenation
operation for lists is isomorphic to that we defined for arrays.

\subsubsection{Statement \label{subsec:Statement-concat-array-as-list}\ref{subsec:Statement-concat-array-as-list}}

The \lstinline!concat! function for lists is defined recursively
as

\begin{wrapfigure}{l}{0.38\columnwidth}%
\vspace{-0.75\baselineskip}
\begin{lstlisting}
def concat[A](p: List[A], q: List[A])
    : List[A] = p match {
  case List() => q
  case a :: t => a :: concat(t, q)
}
\end{lstlisting}

\vspace{-1.25\baselineskip}
\end{wrapfigure}%

\noindent \vspace{-1.9\baselineskip}

\[
p^{:\text{List}^{A}}\pplus q^{:\text{List}^{A}}\triangleq p\triangleright\begin{array}{|c||c|}
 & \text{List}^{A}\\
\hline \bbnum 1 & q\\
A\times\text{List}^{A} & a\times t\rightarrow\bbnum 0+a\times(t\overline{\pplus}q)
\end{array}\quad,
\]
and is equivalent to the \lstinline!concat! function on arrays defined
in Statement~\ref{subsec:Statement-concat-array-associativity}:
\begin{align*}
\forall a^{:\text{Array}_{n_{1}}^{A}},b^{:\text{Array}_{n_{2}}^{A}}.\quad & f_{1}(a)\pplus f_{1}(b)=f_{1}(a\pplus b)\quad,\\
\forall p^{:\text{List}^{A}},q^{:\text{List}^{A}}.\quad & f_{2}(p)\pplus f_{2}(q)=f_{2}(p\pplus q)\quad,
\end{align*}
where $f_{1}$, $f_{2}$ are the isomorphism maps defined in Statement~\ref{subsec:Statement-array-list-equivalence}.

\subparagraph{Proof}

If we show the property for $f_{2}$, we can apply $f_{1}$ to both
sides and obtain the other property.

The base case for lists is $[]\pplus q=q$. This is clearly isomorphic
to concatenating an empty array with another array since $f_{2}([])$
is an empty array. 

The inductive step is $p\pplus q$ where $p$ is a non-empty list,
$p=\bbnum 0+a^{:A}\times t^{:\text{List}^{A}}$. We need to show that
\[
f_{2}(\bbnum 0+a\times t)\pplus f_{2}(q)=f_{2}((\bbnum 0+a\times t)\pplus q)=f_{2}(\bbnum 0+a\times(t\pplus q))\quad.
\]
By definition of $f_{2}$, we have
\begin{align*}
 & f_{2}(\bbnum 0+a\times t)=i\rightarrow\begin{cases}
i=0: & a\\
i\geq1: & \overline{f_{2}}(t)(i-1)
\end{cases}\quad,\\
 & f_{2}(\bbnum 0+a\times(t\pplus q))=i\rightarrow\begin{cases}
i=0: & a\\
i\geq1: & \overline{f_{2}}(t\pplus q)(i-1)
\end{cases}\quad.
\end{align*}
The inductive assumption guarantees that $\overline{f_{2}}(t\pplus q)=f_{2}(t)\pplus f_{2}(q)$.
Using the definition of array concatenation and assuming that the
length of $t$ is $n_{1}$ and the length $q$ is $n_{2}$, we get
\[
f_{2}(\bbnum 0+a\times(t\pplus q))=i\rightarrow\begin{cases}
i=0: & a\\
1\leq i<n_{1}+1: & f_{2}(t)(i-1)\\
n_{1}+1\leq i<n_{1}+1+n_{2}: & f_{2}(q)(i-n_{1}-1)
\end{cases}\quad.
\]
This is the same array as the concatenation $f_{2}(\bbnum 0+a\times t)\pplus f_{2}(q)$.
This concludes the proof.

\subsection{Higher-order type functions. Kinds}

Type constructors are types parameterized by other types. We have
also seen types parameterized by type constructors, e.g.
\begin{lstlisting}
trait Functor[F[_]] { ... }
\end{lstlisting}
It is important to distinguish the ways in which types can be parameterized.
A type constructor such as \lstinline!List! can be understood as
a type-to-type function (TTF): given a type, e.g., \lstinline!Int!,
it produces another type, \lstinline!List[Int]!. It is a type error
to apply \lstinline!List! to a type parameter that is not a simple
type:
\begin{lstlisting}
scala> val x: List[List] = ???
<console>:11: error: type List takes type parameters
       val x: List[List] = ???
                   ^
\end{lstlisting}
To describe the restriction on possible type parameters of \lstinline!List!,
we say that \lstinline!List! has \textbf{kind signature}\index{kind signature}
$*\rightarrow*$. The symbol $*$ means an ordinary type (not a type
function), i.e., a type that can have values. In the type notation,
we can write \textsf{``}kind signatures\textsf{''} as
\[
\text{Int}:*\quad,\quad\quad\text{List}:*\rightarrow*\quad,\quad\quad\text{List}^{\text{Int}}:*\quad.
\]
So, the concept of \textsf{``}\textbf{kind}\textsf{''} can be understood as the \textsf{``}type
signature of a type\textsf{''}. Types of kind $*$ (such as \lstinline!Int!
or \lstinline!String!) can have values, but types of kind $*\rightarrow*$
cannot:
\begin{lstlisting}
scala> val x: Seq = ???
<console>:11: error: type Seq takes type parameters
       val x: Seq = ???
              ^
\end{lstlisting}
Although Scala will check that all kinds match, there is no syntax
in Scala to declare kinds.

The \lstinline!Functor! typeclass is another example of a non-trivial
\textsf{``}kind\textsf{''}: a type whose type parameter is itself a type constructor,
\[
\text{Functor}:(*\rightarrow*)\rightarrow*\quad.
\]
The \lstinline!Functor! type can be seen as a higher-order type-to-type
function (TTF) since it takes a type parameter that is itself a TTF.\index{higher-order type function}
Such types are often called \textsf{``}higher-kinded types\index{types!higher-kinded}\textsf{''}.

For higher-order TTFs, Scala requires syntax such as \lstinline!Functor[F[_]]!
or \lstinline!F[_[_]]!, for example:
\begin{lstlisting}[mathescape=true]
// Ap1 and Ap2 will simply substitute type arguments into type constructors of various kinds.
type Ap1[F[_], A] = F[A]   // $\text{Ap1} : ((*\rightarrow*) \times*)\rightarrow* $
type Ap2[P[_[_], _], Q[_], R] = P[Q, R] // Ap2: $\color{dkgreen}(((*\rightarrow*)\times*\rightarrow*)\times(*\rightarrow*)\times*)\rightarrow* $
type G[A] = Either[(A, A, String), A]   // G: $\color{dkgreen} *\rightarrow* $
type X = Ap2[Ap, G, Int]   // OK; X is now Either[(Int, Int, String), Int]
type Y = Ap2[Ap, Ap, Int]  // Type error: the second argument of Ap2 has wrong kind.
type Z = Ap2[G, G, Int]    // Type error: the first argument of Ap2 has wrong kind.
\end{lstlisting}
The \textsf{``}kind projector\textsf{''} plugin is often needed when writing code
with higher-order TTFs:
\begin{lstlisting}[mathescape=true]
// `Twice` will apply the type constructor Q twice to its type argument, and substitute into P.
type Twice[P[_[_], _], Q[_], R] = P[Lambda[X => Q[Q[X]]], R] // Twice$\color{dkgreen}:(((*\rightarrow*)\times*\rightarrow*)\times(*\rightarrow*)\times*)\rightarrow* $
type O2[A] = Option[(A, A)]                                  // O2: $\color{dkgreen}* \rightarrow *$
type X2 = Twice[Ap1, O2, Int]         // X2 is now Option[(Option[(Int, Int)], Option[(Int, Int)])].
val x2: X2 = Some((Some((1, 2)), Some((3, 4))))   // Types match for `x2`.
\end{lstlisting}


\subsection{Inductive typeclasses and their properties\label{subsec:Inductive-typeclasses}}

We have seen many examples of typeclasses that have similar structural
properties. For instance, a product of semigroups is a semigroup,
a product of monoids is a monoid, a product of functors is a functor,
a product of pointed functors is a pointed functor, and so on. It
turns out that all these typeclasses have a common structure that
simplifies reasoning. The common structure is that all typeclass methods
can be expressed as a \emph{single} uncurried function of a specific
form $P^{A}\rightarrow A$, as Table~\ref{tab:Types-of-typeclass-instance-values}
shows.

\begin{table}
\begin{centering}
\begin{tabular}{|c|c|c|c|}
\hline 
\textbf{\small{}Typeclass} & \textbf{\small{}Instance type as a function} & \textbf{\small{}Inductive form} & \textbf{\small{}Structure functor}\tabularnewline
\hline 
\hline 
{\small{}default value} & {\small{}$\bbnum 1\rightarrow A$} & {\small{}$P^{A}\rightarrow A$} & {\small{}$P^{A}\triangleq\bbnum 1$}\tabularnewline
\hline 
{\small{}semigroup} & {\small{}$A\times A\rightarrow A$} & {\small{}$P^{A}\rightarrow A$} & {\small{}$P^{A}\triangleq A\times A$}\tabularnewline
\hline 
{\small{}monoid} & {\small{}$\bbnum 1+A\times A\rightarrow A$} & {\small{}$P^{A}\rightarrow A$} & {\small{}$P^{A}\triangleq\bbnum 1+A\times A$}\tabularnewline
\hline 
{\small{}functor} & {\small{}$F^{A}\times\left(A\rightarrow B\right)\rightarrow F^{B}$} & {\small{}$S^{\bullet,F}\rightarrow F^{\bullet}$} & {\small{}$S^{B,F^{\bullet}}\triangleq\forall A.\,F^{A}\times\left(A\rightarrow B\right)$}\tabularnewline
\hline 
{\small{}pointed functor} & {\small{}$B+F^{A}\times\left(A\rightarrow B\right)\rightarrow F^{B}$} & {\small{}$S^{\bullet,F}\rightarrow F^{\bullet}$} & {\small{}$S^{B,F^{\bullet}}\triangleq\forall A.\,B+F^{A}\times\left(A\rightarrow B\right)$}\tabularnewline
\hline 
{\small{}contrafunctor} & {\small{}$F^{A}\times(B\rightarrow A)\rightarrow F^{B}$} & {\small{}$S^{\bullet,F}\rightarrow F^{\bullet}$} & {\small{}$S^{B,F^{\bullet}}\triangleq\forall A.\,F^{A}\times\left(B\rightarrow A\right)$}\tabularnewline
\hline 
{\small{}pointed contrafunctor} & {\small{}$\bbnum 1+F^{A}\times\left(B\rightarrow A\right)\rightarrow F^{B}$} & {\small{}$S^{\bullet,F}\rightarrow F^{\bullet}$} & {\small{}$S^{B,F^{\bullet}}\triangleq\forall A.\,\bbnum 1+F^{A}\times\left(B\rightarrow A\right)$}\tabularnewline
\hline 
\end{tabular}
\par\end{centering}
\caption{Structure of typeclass instance values for various inductive typeclasses.\label{tab:Types-of-typeclass-instance-values}}

\end{table}

Functions of type $P^{A}\rightarrow A$ compute new values of type
$A$ from previous values (of type $A$ or other types) wrapped by
the functor $P$. This superficially resembles defining values of
type $A$ by induction and so motivates the following definition:
A typeclass is \textbf{inductive}\index{inductive typeclass}\index{typeclass!inductive}
if a type $A$\textsf{'}s typeclass instance is a value of type $P^{A}\rightarrow A$
with some functor $P$ called the \index{structure functor of a typeclass}\index{typeclass!structure functor}\textbf{structure
functor} of the typeclass. 

A value of type $P^{A}\rightarrow A$ contains all the methods of
the inductive typeclass in a single function. We can implement this
definition by the Scala code
\begin{lstlisting}
final case class InductiveTypeclass[P[_]: Functor, A](methods: P[A] => A)
\end{lstlisting}
For example, the \lstinline!Monoid! typeclass is inductive because
its instances have type 
\[
\text{Monoid}^{A}=\left(A\times A\rightarrow A\right)\times A\cong(\bbnum 1+A\times A\rightarrow A)=P^{A}\rightarrow A\quad\text{ where }P^{A}\triangleq\bbnum 1+A\times A\quad.
\]
So, the \lstinline!Monoid! typeclass can be declared as an inductive
typeclass by code like this,
\begin{lstlisting}
final case class MonoidStructure[A](s: Option[(A, A)])
val monoidStructureFunctor: Functor[MonoidStructure] = ... /* implementation */
type InductiveMonoid[A] = InductiveTypeclass[MonoidStructure, A]
\end{lstlisting}
Implementing the \lstinline!Monoid! typeclass via a structure functor
$P$ and a function $P^{A}\rightarrow A$ is inconvenient for practical
programming. The inductive form $P^{A}\rightarrow A$ is mainly useful
for reasoning about general properties of typeclasses. To illustrate
that kind of reasoning, we will show that the product-type, the function-type,
and the recursive-type constructions work for all inductive typeclasses. 

Consider an arbitrary inductive typeclass \lstinline!TC! defined
via a structure functor \lstinline!P!,
\begin{lstlisting}
type P[A] = ...
type TC[A] = P[A] => A
\end{lstlisting}
If two types $A$, $B$ have an instance of the typeclass \lstinline!TC!,
an instance for the product $A\times B$ can be derived automatically
using the function \lstinline!productTC!:
\begin{lstlisting}
def productTC[A, B](f: P[A] => A, g: P[B] => B): P[(A, B)] => (A, B) =
  p => ( f(p.map(_._1)), g(p.map(_._2)) )
\end{lstlisting}
\begin{align*}
\text{productTC} & :(P^{A}\rightarrow A)\times(P^{B}\rightarrow B)\rightarrow P^{A\times B}\rightarrow A\times B\quad,\\
\text{productTC} & \triangleq(f^{:P^{A}\rightarrow A}\times g^{:P^{B}\rightarrow B})\rightarrow p^{:P^{A\times B}}\rightarrow(p\triangleright\pi_{1}^{\uparrow P}\triangleright f)\times(p\triangleright\pi_{2}^{\uparrow P}\triangleright g)\quad.
\end{align*}
This explains why product types have instances for all typeclasses
listed in Table~\ref{tab:Types-of-typeclass-instance-values}: those
typeclasses are inductive. (However, this argument does not prove
that the \emph{laws} of a given typeclass will also hold for the product
types.)

It is interesting to note that the co-product construction cannot
be derived in general for arbitrary inductive typeclasses: given $P^{A}\rightarrow A$
and $P^{B}\rightarrow B$, it is not guaranteed that we can compute
$P^{A+B}\rightarrow A+B$. Not all inductive typeclasses support the
co-product construction (although many do).

The function-type construction promises a typeclass instance for $E\rightarrow A$
if the type $A$ has a typeclass instance. This construction works
for any inductive typeclass because a value of type $P^{E\rightarrow A}\rightarrow E\rightarrow A$
can be computed from a value of type $P^{A}\rightarrow A$ when $P$
is a functor:
\[
q:(P^{A}\rightarrow A)\rightarrow P^{E\rightarrow A}\rightarrow E\rightarrow A\quad,\quad\quad q\triangleq h^{:P^{A}\rightarrow A}\rightarrow p^{:P^{E\rightarrow A}}\rightarrow e^{:E}\rightarrow p\triangleright(x^{:E\rightarrow A}\rightarrow e\triangleright x)^{\uparrow P}\triangleright h\quad.
\]
As in the case of the product construction, the laws still need to
be checked for the new instances.

Finally, let us show that the recursive type construction works for
inductive typeclasses. Consider a recursive type $T$ defined by a
type equation $T\triangleq S^{T}$, where the functor $S^{\bullet}$
\textsf{``}preserves\textsf{''} typeclass instances: if $A$ has an instance then
$S^{A}$ also does, as we saw in all our examples in this chapter.
In other words, we have a function $\text{tcS}:(P^{A}\rightarrow A)\rightarrow P^{S^{A}}\rightarrow S^{A}$
that creates typeclass instances of type $P^{S^{A}}\rightarrow S^{A}$
out of instances of type $P^{A}\rightarrow A$. Then we define an
instance \lstinline!tcT! for $T$ as 
\[
\text{tcT}^{:P^{T}\rightarrow T}\triangleq p^{:P^{T}}\rightarrow\text{tcS}\,(\overline{\text{tcT}})(p)\quad.
\]
This recursive definition terminates because it is implemented as
an expanded function. The types match since we can convert between
the equivalent types $T$ and $S^{T}$ whenever necessary, so $p^{:P^{T}}$
can be converted to a value of type $P^{S^{T}}$, while the value
$\text{tcS}\,(\text{tcT})(p)$ can be converted from type $S^{T}$
back to type $T$. In Scala code, the conversions between $T$ and
$S^{T}$ are implemented by the constructor \lstinline!T(...)! and
accessor \lstinline!(_.s)! methods of the case class that wraps the
type $T$.
\begin{lstlisting}[mathescape=true]
type S[A] = ...               // Define a functor S as required.
final case class T(s: S[T])   // Define the recursive type T as ${ \color{dkgreen}\scriptstyle{T\triangleq \,S^{T}} }$.
def tcS: TC[A] => TC[S[A]] = ... // Compute instances for S[A] from instances of A.
def tcT: P[T] => T = p => T(tcS(tcT)(p.map(_.s))) // Define the recursive instance.
\end{lstlisting}
In this way, we can implement the recursive-type construction with
any inductive typeclass. (The typeclass laws still need to be checked
for the recursively defined instances.)

The \lstinline!Functor! and \lstinline!Pointed! typeclasses are
also inductive. Instead of a structure functor, we need to use a higher-order
type function denoted by $S^{A,F^{\bullet}}$ and parameterized by
a type constructor $F^{\bullet}$ as well as by a type parameter $A$.
(The type $S$ has kind $*\times(*\rightarrow*)\rightarrow*$.) The
methods of these typeclasses are expressed as $S^{\bullet,F}\rightarrow F^{\bullet}$,
which is analogous to $P^{A}\rightarrow A$ except for additional
type parameters. Similar arguments can be made for these typeclasses,
although it is more difficult to reason about type constructors (and
the laws will not hold without additional assumptions). As we have
seen, the product-type, the function-type, and the recursive-type
constructions work for functors, contrafunctors, pointed functors,
and pointed contrafunctors.

Important inductive typeclasses are functors and contrafunctors (Chapter~\ref{chap:Functors,-contrafunctors,-and}),
filterables (Chapter~\ref{chap:Filterable-functors}), monads (Chapter~\ref{chap:Semimonads-and-monads}),
and applicatives (Chapter~\ref{chap:8-Applicative-functors,-contrafunc}).
We will see in Chapter~\ref{chap:Free-type-constructions} that another
general construction also works for all inductive typeclasses, \textemdash{}
the \textsf{``}free\textsf{''} type construction.

We have also seen examples of typeclasses that are \emph{not} inductive.
The \lstinline!Extractor! typeclass has instances of type $A\rightarrow Z$,
which is not of the form $P^{A}\rightarrow A$ for any functor $P$.
Another such typeclass is \lstinline!Copointed!, whose method $F^{A}\rightarrow A$
is not of the form $S^{\bullet,F}\rightarrow F^{\bullet}$. However,
the methods of these typeclasses can be written in the inverted form
$A\rightarrow P^{A}$ with some functor $P$. We call them \index{typeclass!co-inductive}\textbf{co-inductive}
\textbf{typeclasses}\index{co-inductive typeclass}. A motivation
for this name is that the \emph{co-product} construction (rather than
the product construction) works with co-inductive typeclasses: given
values of types $A\rightarrow P^{A}$ and $B\rightarrow P^{B}$, we
can produce a value of type $A+B\rightarrow P^{A+B}$, i.e., a co-product
instance, but not necessarily a value of type $A\times B\rightarrow P^{A\times B}$,
which would be a product-type instance. The function-type construction
is not guaranteed to work with co-inductive typeclasses, but the recursive-type
construction and the \textsf{``}free\textsf{''} type construction can be implemented
after appropriate modifications.

The \lstinline!Eq! typeclass is \textsf{``}uninductive\textsf{''} (neither inductive
nor co-inductive) because its instance type, $A\times A\rightarrow\bbnum 2$,
is neither of the form $P^{A}\rightarrow A$ nor $A\rightarrow P^{A}$.
The traversable functor (Chapter~\ref{chap:9-Traversable-functors-and})
is another example of an uninductive typeclass. Uninductive typeclasses
usually support fewer type constructions. For example, only \emph{polynomial}
types can have instances of \lstinline!Eq! or \lstinline!Traversable!
typeclasses.

\subsection{Typeclasses with more than one type parameter (type relations)}

A typeclass constraint in a function, such as \lstinline!func[A: Monoid]!,
restricts a type parameter to a certain type domain. Sometimes it
is necessary to restrict \emph{several} type parameters to satisfy
some conditions together. Let us look at two simple examples of this. 

The first example is converting integer numbers to floating point.
The ranges of the available types allow us to convert a \lstinline!Short!
to a \lstinline!Float! and an \lstinline!Int! to a \lstinline!Double!.
Can we implement the type signature 
\begin{lstlisting}
def convertNumber[M, N](x: M): N
\end{lstlisting}
where the type parameters \lstinline!M!, \lstinline!N! are constrained
to be either \lstinline!M = Short! and \lstinline!N = Float!, or
\lstinline!M = Int! and \lstinline!N = Double!? (Of course, we will
want to be able to add further supported pairs of types later.)

A condition that constrains several type parameters at once is called
a \index{type relation}\textbf{type relation}. 

The second example is converting mutable data structures into the
corresponding immutable ones. The Scala library contains data structures
such as sequences, sets, and dictionaries, each having a mutable and
an immutable version. Can we implement a function with type signature
\begin{lstlisting}
def convertData[Mut[_], Immut[_], A](data: Mut[A]): Immut[A]
\end{lstlisting}
where the type parameters \lstinline!Mut! and \lstinline!Immut!
are constrained to represent the mutable / immutable versions of a
supported data structure (for example, \lstinline!Mut = mutable.Set!
and \lstinline!Immut = immutable.Set!, etc.)?

A typeclass constraint for a single type parameter, such as \lstinline!func[A: Monoid]!,
is implemented by requiring an \textsf{``}evidence value\textsf{''}\index{evidence value}\index{typeclass!evidence value}
of type \lstinline!Monoid[A]! as an additional argument of the function
\lstinline!func!. Implementing a type relation for \emph{two} type
parameters \lstinline!A!, \lstinline!B! is similar: We define a
type constructor, say \lstinline!Rel[_, _]!, and create some evidence
values of type \lstinline!Rel[A, B]! with chosen type parameters
\lstinline!A!, \lstinline!B!. Any function, say \lstinline!f[A, B]!,
that needs a relation constraint on its type parameters will take
an extra evidence argument of type \lstinline!Rel[A, B]!. This will
prevent our code from using \lstinline!f[A, B]! with types \lstinline!A!,
\lstinline!B! that are not in the required relation. 

Using this technique, we can define a relation \lstinline!MayConvert!
and write the code for \lstinline!convertNumber!:
\begin{lstlisting}
final case class MayConvert[A, B](convert: A => B)  // Evidence value contains a conversion function.
implicit val ev1 = MayConvert[Short, Float](_.toFloat)          // Evidence value for [Short, Float].
implicit val ev2 = MayConvert[Int, Double](_.toDouble)          // Evidence value for [Int, Double].
def convertNumber[M, N](x: M)(implicit ev: MayConvert[M, N]): N = ev.convert(x)
\end{lstlisting}
With these definitions, it will be a compile-time error to use \lstinline!convertNumber!
with unsupported types:
\begin{lstlisting}
scala> convertNumber(123)
res0: Double = 123.0

scala> convertNumber(123:Short)
res1: Float = 123.0

scala> convertNumber("abc")
<console>:17: error: could not find implicit value for parameter ev: MayConvert[String,N]
       convertNumber("abc")
                    ^
\end{lstlisting}

As we have just seen, a type relation is defined by creating a set
of evidence values. The code above defines \lstinline!MayConvert!
as a one-to-one type relation because the evidence values (or \textsf{``}relation
instances\textsf{''}) \lstinline!ev1! and \lstinline!ev2! do not have any
types in common. So, \lstinline!MayConvert! is equivalent to a type-to-type
\emph{function} that maps \lstinline!Short! to \lstinline!Float!
and \lstinline!Int! to \lstinline!Double!. However, type relations
are not limited to one-to-one relations or to type functions. By creating
suitable implicit evidence values, we can implement many-to-one or
many-to-many relations when needed. 

A practical example of a many-to-many \index{type relation!many-to-many}type
relation is the compatibility between physical units. Miles can be
converted into kilometers; pounds can be converted into ounces or
kilograms; but kilograms cannot be converted into miles. Type relations
allow us to implement type-safe operations for quantities with units.
Adding kilograms to pounds will automatically convert the quantity
to a common unit, while adding kilograms to miles will raise a compile-time
error.

Begin by declaring a type for \textsf{``}quantity with units\textsf{''} and some type
names for the supported units:\index{constant functor}
\begin{lstlisting}
trait KG; trait LB; trait OZ; trait KM; trait MI; trait FT // Declare names for some supported units.
final case class Quantity[U](value: Double)    // Constant functor: No values of type `U` are stored.
def add[U1, U2](x: Quantity[U1], y: Quantity[U2]): Quantity[U2] = ???
\end{lstlisting}
The parameter \lstinline!U! in \lstinline!Quantity[U]! is called
a \textbf{phantom}\index{phantom type parameter} type parameter because
\lstinline!Quantity[U]! contains no values that use \lstinline!U!.
The parameter \lstinline!U! would not be phantom if \lstinline!Quantity[U]!
were not a constant functor\index{constant functor!example of use}
but instead contained values e.g., of type \lstinline!U! or of type
\lstinline!U => Double! or of some other type that uses \lstinline!U!. 

The function \lstinline!add[U1, U2](x, y)! must impose a type relation
constraint on \lstinline!U1! and \lstinline!U2!, so that \lstinline!x!
and \lstinline!y! may be added only when they have compatible units.
The type relation is implemented as a type constructor \lstinline!Convertible!
with two type parameters. A \textsf{``}relation instance\textsf{''} (i.e., a value
of type \lstinline!Convertible[U1, U2]!) will contain a multiplier
for converting any quantity from units \lstinline!U1! to units \lstinline!U2!:
\begin{lstlisting}
final case class Convertible[U1, U2](multiplier: Double)
implicit val c1 = Convertible[KG, KG](1.0)
implicit val c2 = Convertible[LB, KG](0.453592) // Pounds in kilograms.
implicit val c3 = Convertible[KM, KM](1.0)
implicit val c4 = Convertible[MI, KM](1.60934)  // Miles in kilometers. Add more definitions here.
\end{lstlisting}
Now we can implement the \lstinline!add! function and verify that
the type relation works as we intended:
\begin{lstlisting}
def add[U1, U2](x: Quantity[U1], y: Quantity[U2])(implicit ev: Convertible[U1, U2]): Quantity[U2] =
  Quantity(x.value * ev.multiplier + y.value)

scala> add(Quantity[LB](1), Quantity[KG](1))   // 1 pound + 1 kg = 1.453592 kg.
res0: Quantity[KG] = Quantity(1.453592)

scala> add(Quantity[MI](1), Quantity[KG](1))   // Compile-time error: cannot add miles to kilograms.
<console>:25: error: could not find implicit value for parameter ev: Convertible[MI,KG]
\end{lstlisting}

To make this code more convenient for practical use, we can add extension
methods that shorten the syntax from \lstinline!Quantity[KG](1)!
to \lstinline!1.kg! and from \lstinline!add(2.lb, 2.kg)! to a more
readable \lstinline!2.lb + 2.kg!:
\begin{lstlisting}
implicit class QuantitySyntax(x: Double) {
  def kg = Quantity[KG](x)
  def lb = Quantity[LB](x)        // Add more definitions as needed.
}
implicit class QuantityAdd[U1](x: Quantity[U1]) {
  def +[U2](y: Quantity[U2])(implicit ev: Convertible[U1, U2]): Quantity[U2] = add(x, y)
}

scala> 2.lb + 2.kg        // Compute 2 pounds + 2 kilograms; the result is in kilograms.
res1: Quantity[KG] = Quantity(2.907184)
\end{lstlisting}

Another necessary improvement is reducing the number of implicit values.
The current code uses $n^{2}$ implicit values for every group of
$n$ compatible units. Adding support for a new unit (say, inches)
requires adding implicit values for converting between inches and
all previously defined units of length. To avoid this problem, the
code must be reorganized to convert all compatible quantities to chosen
units (e.g., all length to kilometers and all mass to kilograms).
This makes the \lstinline!Convertible! relation many-to-one\index{type relation!many-to-one}
instead of many-to-many. The resulting code is shown in Figure~\ref{fig:Full-code-implementing-units-length-mass}.

\begin{figure}
\begin{lstlisting}[frame=single,fillcolor={\color{black}},framesep={0.2mm},framexleftmargin=2mm,framexrightmargin=2mm,framextopmargin=2mm,framexbottommargin=2mm]
trait KG; trait LB; trait OZ; trait KM; trait MI; trait FT             // Some supported units.

// This type relation is many-to-1: it relates all mass units to KG and all length units to KM.
final case class Convertible[U1, U2](multiplier: Double) extends AnyVal
// Units of mass.
implicit val cKG = Convertible[KG, KG](1.0)
implicit val cLB = Convertible[LB, KG](0.453592)
implicit val cOZ = Convertible[OZ, KG](0.0283495)
// Units of distance.
implicit val cKM = Convertible[KM, KM](1.0)
implicit val cMI = Convertible[MI, KM](1.60934)
implicit val cFT = Convertible[FT, KM](0.0003048)
// We can add support for new units whenever necessary.

final case class Quantity[U](value: Double) extends AnyVal { // Use `AnyVal` to reduce run-time cost.
  def +[U2, C](q: Quantity[U2])(implicit ev1: Convertible[U, C], ev2: Convertible[U2, C]) =
      Quantity[U2](value * ev1.multiplier / ev2.multiplier + q.value)

  def ==[U2, C](q: Quantity[U2])(implicit ev1: Convertible[U, C], ev2: Convertible[U2, C]) =
      value * ev1.multiplier == q.value * ev2.multiplier
}

implicit class QuantitySyntax(x: Double) {    // Extension methods defined for convenience.
  def kg = Quantity[KG](x)
  def lb = Quantity[LB](x)
  def oz = Quantity[OZ](x)
  def km = Quantity[KM](x)
  def mi = Quantity[MI](x)
  def ft = Quantity[FT](x)
  // This general extension method, e.g., `1.in[KM]`, will also work for any units defined later.
  def in[U](implicit ev: Convertible[U, _]): Quantity[U] = Quantity[U](x)
}

scala> 1.in[KM]         // Use the general method `.in` with a type parameter.
res1: Quantity[KM] = Quantity(1.0)

scala> 10000.ft + 1.km  // Use the `.ft` and `.km` extension methods.
res2: Quantity[KM] = Quantity(4.048)

scala> 1.kg + 2.lb == 32.oz + 1.kg   // Compare values safely.
res2: Boolean = true

scala> 1.km + 2.lb      // Compile-time error: cannot add kilometers to pounds.
<console>:29: error: could not find implicit value for parameter ev2: Convertible[LB,C]
       1.km + 2.lb
            ^

scala> trait YD; implicit val cYD = Convertible[YD, KM](0.0009144)  // Add support for yards.
defined trait YD
cIN: Convertible[YD,KM] = Convertible(9.144E-4)

scala> 1.in[YD] + 1.ft // Use .in[YD] to compute 1 YD + 1 FT = 4 FT.
res3: Quantity[FT] = Quantity(4.0)
\end{lstlisting}

\caption{Implementing type-safe computations with units of length and mass.\label{fig:Full-code-implementing-units-length-mass}}
\end{figure}


\subsection{Inheritance and automatic conversions of typeclasses\label{subsec:Inheritance-and-automatic-typeclass}}

It often happens that one typeclass is a subset of another; for example,
a \lstinline!Monoid! instance for a type $T$ means that $T$ already
has the properties of both \lstinline!Semigroup! and \lstinline!HasDefault!
typeclasses. One says that the \lstinline!Monoid! typeclass \textbf{inherits}\index{typeclass!inheritance}
from the \lstinline!Semigroup! and \lstinline!HasDefault! typeclasses.
We may want to express inheritance relations between typeclasses,
so that, e.g., a \lstinline!Monoid! instance should automatically
imply the presence of a \lstinline!Semigroup! instance, without extra
code.

One way of inheriting a typeclass is to add a constraint to the new
typeclass constructor:
\begin{lstlisting}
final case class Semigroup[T](combine: (T, T) => T)
final case class Monoid[T: Semigroup](empty: T)  // Inherit `Semigroup`.
\end{lstlisting}
The case class \lstinline!Monoid! combines a previous \lstinline!Semigroup!
instance with the new method \lstinline!empty!. Creating an instance
of \lstinline!Monoid! for a type \lstinline!T! will then require
having an instance of \lstinline!Semigroup! for \lstinline!T!:
\begin{lstlisting}
implicit val c1 = Semigroup[Int](_ + _)
implicit val c2 = Monoid[Int](0)  // Works only if a `Semigroup[Int]` is available.
\end{lstlisting}

Given a \lstinline!Monoid[T]! instance, how can we recover the inherited
implicit value of type \lstinline!Semigroup[T]!? This is achieved
by redefining the \lstinline!Monoid! class like this,
\begin{lstlisting}
final case class Monoid[T](empty: T)(implicit val semigroup: Semigroup[T])   // Use `implicit val`.
implicit def semigroupFromMonoid[T](implicit ti: Monoid[T]): Semigroup[T] = ti.semigroup
\end{lstlisting}

Another possibility of implementing typeclass inheritance is to use
object-oriented inheritance of traits. This approach is often used
when defining typeclasses as traits with methods:
\begin{lstlisting}
trait Semigroup[T] { def combine: (T, T) => T }
trait Monoid[T] extends Semigroup[T] { def empty: T } // `def combine` is inherited from `Semigroup`.
\end{lstlisting}
Creating an instance of \lstinline!Monoid! for a type \lstinline!T!
no longer requires having an instance of \lstinline!Semigroup! for
\lstinline!T!:

\begin{wrapfigure}{l}{0.48\columnwidth}%
\vspace{-0.95\baselineskip}
\begin{lstlisting}
implicit val c: Monoid[Int] = new Monoid[Int] {
  def empty: Int =  0
  def combine: (Int, Int) => Int =  _ + _
}
\end{lstlisting}

\vspace{-1.1\baselineskip}
\end{wrapfigure}%

\noindent With this approach, we cannot avoid repeating the code for
\lstinline!def combine...! even if we \emph{do} already have a \lstinline!Semigroup!
instance. However, conversion from \lstinline!Monoid[T]! to \lstinline!Semigroup[T]!
is now automatic due to \textbf{object-oriented inheritance}\index{object-oriented inheritance}:
Scala considers \lstinline!Monoid[T]! a subtype of \lstinline!Semigroup[T]!
because the \lstinline!Monoid! class is declared as \lstinline!extends Semigroup!.

A problem with the object-oriented inheritance is that automatic conversions
to parent typeclasses cannot be \emph{disabled}. When several typeclasses
inherit from the same parent typeclass, duplicate implicit instances
of the parent typeclass will be present, which is a compile-time error:
\begin{lstlisting}
trait TC[A]                    // Parent typeclass.
trait TC1[A] extends TC[A]     // Two different typeclasses TC1 and TC2 inherit from TC.
trait TC2[A] extends TC[A]
// The function f requires A to have both TC1 and TC2 instances and then wants to access TC instance.
def f[A: TC1 : TC2]() = {
  implicitly[TC[A]]  // Compilation fails because two implicit values of type TC[A] are found.
}
\end{lstlisting}

When typeclass inheritance is implemented by combining instances without
object-oriented inheritance, conversions to parent typeclasses are
not automatic: they are implemented by implicit functions that need
to be imported into the current scope. The programmer\textsf{'}s code can avoid
producing duplicate instances by choosing which implicit conversions
to import:
\begin{lstlisting}
final case class TC[A]()
final case class TC1[A]()(implicit val tc: TC[A])                      // TC1 inherits TC.
object TC1 { implicit def toTC[A](implicit x: TC1[A]): TC[A] = x.tc }
final case class TC2[A]()(implicit val tc: TC[A])                      // TC2 inherits TC.
object TC2 { implicit def toTC[A](implicit x: TC2[A]): TC[A] = x.tc }
// The function f requires A to have both TC1 and TC2 instances and then wants to access TC instance.
def f[A: TC1 : TC2]() = {
      import TC1._  // Can import TC1._ or TC2._ but not both. If the next line is uncommented,
//    import TC2._  // compilation will fail because two implicits of type TC[A] will be found!
  implicitly[TC[A]] // This compiles successfully. One implicit instance of TC[A] can be found.
}
\end{lstlisting}

The problem of duplicate inherited instances can be solved with less
work for the programmer if the typeclasses are implemented using a
special, more complicated encoding.\footnote{See slides 5\textendash 14 of the talk by \index{John de Goes}John
de Goes: \texttt{\href{https://www.slideshare.net/jdegoes/scalaz-8-a-whole-new-game}{https://www.slideshare.net/jdegoes/scalaz-8-a-whole-new-game}}}

\begin{comment}
this tutorial is about typeclasses and type level functions to motivate
why we want to talk about this let\textsf{'}s consider what happens if we would
like to implement the sum function generically so that the same implementation
code will work for sequence of integers for sequence of doubles and
so on if we try to do that we find that it doesn't quite work we cannot
generalize the sum function like this with a type parameter T and
an argument of type sequence of T because there is no way for us to
sum or to add values of type T where T is unknown it\textsf{'}s arbitrary unknown
type obviously the sum function can only work for types T that in
some sense or summable another very similar situation happens if we
wanted for instance to define the F map function for factors that
already define the map function as we know F map is equivalent to
map so for each factor somebody defined already the map function we
would like to define F map for all of them at once by in the same
generic code but we cannot generalize F map to arbitrary type constructors
F here is what we would have to write suppose that we tried we would
have to put F as a type parameter F being the type constructor of
the function just as an aside in Scala this syntax is necessary if
you want to put a type parameter that is itself a type construction
you can do that just by using this syntax so if we try to write F
map like this we will have F me up with type parameters and we cannot
write this code because F in here is an arbitrary type constructor
parameter and there\textsf{'}s no way for us to get the map function for that
F we don't even know if it exists just like here there\textsf{'}s no way for
us to get the addition operation with some more plus or something
for the type T and just like in that case the F map could work only
for certain type constructors F namely for those that are factors
so our desire to write code more generically leads us to the need
to define functions whose type arguments for example the T and F are
not just arbitrary types but there are types that are required to
have certain properties or to belong to a certain subset of possible
types here for instance it will be integer double long and so on maybe
others string could be considered as well and here will be the filter
types or rather to be precise the factor type constructors that should
so somehow we should require require that this type parameter in the
F map implementation is not just any type but it is a sub is belongs
to a subset a certain subset of possible types which we also have
to define somehow so if we are able to do that which is the whole
focus of this tutorial if we're able to do that then we can use known
properties of this type parameters in implementation of these functions
also we would like to be able to add new supported types whenever
it\textsf{'}s needed so integer double maybe a library will define this property
for the type T but we want to add new ones later so wanted to be extensible
so this is our goal now the first step towards solving it and we will
be solving this systematically the first step is to realize that this
is similar to the concept of partial functions except that applied
to types let me then look at what partial functions are generally
functions can be total or partial the total function always has a
result for any argument value the partial function sometimes has no
result for some argument values it does have a result for others it
does not an example of a total function would be an integer function
taking an integer argument with returning that integer multiplied
by 3 so for any input integer you always have an output integer the
example of a partial function will be real valued square root it has
no result for negative arguments no real valued square root from negative
arguments but it does have a result for non-negative arguments so
that\textsf{'}s a partial function partial function has a domain of its definition
which is smaller than the all values of that type now we should also
consider that here we have type parameters so what does it mean that
we have a function with type parameters it\textsf{'}s like a function with
argument is a type so let\textsf{'}s consider functions both from value and
from type to values in two types and that is the most most general
kind of situation so we will have this table of all possible functions
function from value or from type and to value and to type so the function
fill value to value were value level function or value to value function
that\textsf{'}s just an ordinary function like that it takes a value argument
of type integer let\textsf{'}s say and returns a value of type integer so that\textsf{'}s
a value to value function a function from type to value could be visualized
like this so it has a type parameter and the result is a value of
this type now this type depends on the type parameter so first you
have to give it the type parameter then it knows what type it value
needs to return and then it creates somehow that value and returns
it now one important observation here is that these functions are
the same kind the same sort this function has a type parameter and
then you can rewrite this in a different syntax by writing some column
sequence t rlt which will be quite similar to this just a different
syntax so just like in the example here first you have to get the
type parameter T then you know which types you're taking in this function
so the function some can be considered as a function film type from
t2 value which is a function from sequence T 2 T so this is a value
which is itself a function on a function at the value level but that\textsf{'}s
a value right so functions at value level or values sequence T 2 T
where T is already fixed fixed type this type parameter finally we
also have functions from type 2 type for example if we define this
type then my data is a function from type 2 type so later in the code
you could say my data of string and that would be the same as evaluating
this function substituting string instead of a and the result would
be either of int and string and there also is a function from value
to type in principle now in Scala it would be quite hard to come up
with useful examples of this sort because these are actually dependent
types so this is this kind of function is called a dependent type
which means that it\textsf{'}s a type that depends on a value and that is not
very well supported in Scala or in Haskell for that matter so there
are more advanced experimental aim which is like a dress or Agda not
have better support for dependent types so we will not talk about
dependent types here our concern will be mostly this part of the table
functions from type either from type to value or from type 2 type
now consider how these functions are being evaluated the value to
value functions are evaluated at runtime type 2 value functions are
evaluated at compile time because you cannot really call these functions
without specifying a type parameter and that is evaluated at compile
time the compiler will know that you are calling this function with
string here say instead of a and that would be known at compile time
as you write your code one caveat here is that if you use type casts
in the code then you could make a run time evaluation based on types
so type T value functions can become runtime which is a problem because
it is possible to have a bug and a bug in a type 2 value or type 2
type function at compile time that\textsf{'}s okay because you you will find
it before you run your program at runtime it\textsf{'}s not okay you already
deployed your program it\textsf{'}s running and three months later it crashes
because of some bug that\textsf{'}s not a good outcome at all so we will avoid
using type casts or any kind of runtime computation with types we
want to keep all type computations compile time in this way they are
safe consider now partial functions so these so far we just considered
any kind of functions here of all kinds value to value value to type
type to a value type to type consider now partial functions so partial
value to value function is something like this it\textsf{'}s a partial function
that takes an argument if the argument here is an option that is not
empty when it returns the value inside this option but if the argument
of this function were the empty option which is to say the none value
then there is no case to match that so this function cannot process
that argument only so this function considered as a functional options
is a partial function if you apply this to the room kind of argument
you get an exception at runtime consider now functions from types
of partial type the value function is a function that takes a type
argument and it only works for certain types for certainty types T
in the view call this function so this is an example of this would
be this function which I will talk about it later but basically the
idea is that it\textsf{'}s a function that has a type parameter it returns
a value and when you call this function with the wrong type parameter
it\textsf{'}s an error at compile time otherwise it works so that\textsf{'}s a partial
function at type two value level so partial type two value function
is what we would like to have like to have those functions and the
goal of this tutorial is to explain systematically how to create and
manage partial type two value functions typeclasses is the mechanism
for doing that and the idea roughly speaking is that the type T should
belong to a certain typeclass or a certain subset of types or a certain
type of domain there are certain kind of types and then you can apply
that partial type to value function to that type if we are able to
implement this then these problems would be solved we will just say
well some is not just total type the value function is a partial type
the value function it\textsf{'}s only defined on types T that belong to the
correct kind or typeclass which are summable in some sense and of
course this code it won't work it has to be done honest it\textsf{'}s like
a different way which we will find out how to do in a systematic manner
before we do that let\textsf{'}s look at an example of using value level partial
functions and let\textsf{'}s see what\textsf{'}s the issue there so imagine we have
a situation we have a sequence of either end boolean we want to find
the {[}Music{]} elements in that sequence that are in the left part
of the disjunction having an integer and we just get one to get a
sequence of those integers out of this sequence how do we do that
well we just say take in a sequence we filter those that are on the
left which is like this maybe and then we map with this partial function
now after this step the result is still of type sequence of either
so now we are applying this partial function to arguments of type
either which is unsafe what about with a right element and there will
be nothing to match well actually we know in this case it\textsf{'}s okay to
apply this partial function because we just filtered all the elements
to be on the left side of the disjunction so we know it\textsf{'}s safe however
the types don't show that it is safe the compile-time checking can
tell you maybe that there is some problem a warning but certain cases
will not be matched but it doesn't know it\textsf{'}s safe and so if you refactor
this code in some way but say you put this part in one module in this
part in another module and then different people start to modify this
and eventually this condition has changed and it has more complicated
conditions whatever features we need to implement and finally it\textsf{'}s
not always the left and so the other part of the code is also changed
in some way and you get a runtime error after some refactoring sometime
later the type side type safe version of this code does not use filter
milk and sort of filter map you do collect so collect is basically
a safe version of filtering only those that fit into this partial
function and then applying the partial function so partial functions
in Scala are special a special type and this type has a method to
decide whether the partial function can apply to us and give an argument
and so that\textsf{'}s what we collect is doing and the result is safe it is
of type sequence int and there\textsf{'}s nothing you can refactor here to
break the safety of this code so partial functions are safe but only
in certain places where you take care to encapsulate the possible
breakage so usually we make functions total we either add more code
to handle other cases or we use more restrictive types so that we
know that this is not just an either it\textsf{'}s really always left and in
other cases for instance there types such as non-empty list or positive
number or or even this this is a subtype of option and if you have
this than you you know it\textsf{'}s not empty so instead of using option you
use this in a specific function or you use known empty list and sort
of just list and if you do that you can do it dot head on a non empty
list and it\textsf{'}s always safe and the safety is checked at compile time
you cannot pass here instead of non empty list just arbitrary list
so that\textsf{'}s how we handle the unsafe team partial functions for value
level functions so for type level functions we would like to restrict
the type parameters to some restrictive subset of types so that this
is safe that\textsf{'}s our motivation so let\textsf{'}s see how this can be done here
is the first example of a partial type level function consider this
data type so this is a disjunction the disjunction is paralysed by
a type parameter a and has two cases in the one case gives you a my
type constructor of int and the other case gives you my type constructor
of string well this is just an artificial example but this could occur
in some applications now notice we have defined the type constructor
my TC my type constructor as if it\textsf{'}s defined for any parameter a as
any type a actually in code you can only ever create values either
of my TC event or of type my DCF string you will never be able to
define any values of any other type like my TC of bullying or mighty
sea or anything else only either string or integer there is no other
case and everything is sealed and final and so there\textsf{'}s no way to add
any more cases let\textsf{'}s see how a code looks like for this so here\textsf{'}s
the code if I wanted to pretend that I have a value of type my TC
of a for arbitrary a I cannot do that I have to create it instantly
the only way to credit is to use case one or case two neither one
would work so none of them type checks action for example if I did
this I mean it may get no no no way I can do anything here I could
say no this one is my t siient so the only thing that can work here
is this but I cannot put here a equal to int either I have a parameter
here or not so you can get rid of this parameter there\textsf{'}s no way I
can use this mighty sea with an arbitrary time frame type round you
can get a value now I can define types such as this one which looks
like I'm applying the type level function to int and get a type so
you see I using this type constructor as as if it were a function
of types I apply this to type into my data type t1 up out of that
and this works and then I can use t1 and t2 for example in my code
and it\textsf{'}s all compiles when it works so this is to illustrate but the
type constructor like my TC is quite similar to a function at type
level since a functional takes types as arguments and returns types
just that I have to say type instead of well because it\textsf{'}s a type level
function not a value level function otherwise it\textsf{'}s very similar to
a function so that\textsf{'}s why I keep calling this a type 2 type function
or type the value function because I'm I want to think about these
type constructors in a general way I don't want to think about them
in some kind of special magic fashion these are just functions their
arguments are types the results are types and now I can use my mathematical
intuition about functions to reason about them now here\textsf{'}s a way to
use this in code so for example x2 is of this type I can match this
and I get a result so it works now what if I wanted to apply this
function to a different argument so I am applying it to doing now
there is no way to create a value of type boolean but the Scala compiler
doesn't know this so in some sense I consider this function as a function
that is only defined so it\textsf{'}s a type 2 type function my TC that\textsf{'}s only
defined for int or string as type arguments but if I write my TC of
boolean and I evaluate this it compiles so the compiler doesn't know
doesn't check but there is no way to create this value but actually
no code would ever compile it creates this value correctly like this
for example this won't compile now what I can do is I can force the
type like this using this construction as instance of which breaks
type checking its runtime typecast and it\textsf{'}s completely breaking the
type checking there is nothing the compiler will check here the results
are going to be wrong like this is going to be wrong I can't really
use this in any useful way in other words it doesn't help if you break
the type checking type checking is your friend this is to be used
only in very rare situations when the type system is not strong enough
not powerful enough to do some extremely complicated things and in
most cases it\textsf{'}s not necessary so this is cheating in terms of type
checking and even this cheating pretend that I created a value of
type t3 but actually I have not created such a value I cannot use
it in the code still there\textsf{'}s nothing I can do with this in code that
would be compiled invented working so this motivates me to consider
that a function my TC is actually a partial type function it is meaningless
to apply this function to arguments such as doing the type argument
such as bullying it\textsf{'}s only meaningful to apply to arguments integer
and string so in other words this type function has a domain type
domain it is set of types to which it can be applied meaningfully
and this domain contains only two types int and string so become the
compiler as we have just seen does not enforce this it does not flag
it immediately as an error however it does enforce that the values
of this type only exist for the type parameter within the correct
domain or the type domain and this type domain is defined at compile
time and is what I mean by the domain of the partial type 2 type function
just a side note here the type constructor my TC cannot possibly be
a factor since it\textsf{'}s not defined for all type arguments a factor must
be a total type 2 type function partial type 2 type functions cannot
be factors so these kind of types where you have partial type 2 type
functions and case classes they're called generalized algebraic data
types or generalized means that these types are not the type parameter
a there are just specific types so there are some cases when they're
useful they're useful for domain modeling of certain kinds like for
example you have some kind of query and the result types can be a
fixed set of different result types then it\textsf{'}s useful to have all these
possible result types modeled directly via cases in the disjunction
like this for domain-specific languages representing some kind of
type expressions in some way then it\textsf{'}s also useful these are specific
problems where people have used GE T\textsf{'}s in a useful way so this is
our first example of a partial type function another way of doing
this is to have a trait with code now here this is just a data type
there is no code in here so let\textsf{'}s see how that works when you have
trade with code so that\textsf{'}s more the object-oriented way because it
uses method overriding so we start with the trait that has a method
the trait has a type parameter as well and there are some case classes
so it\textsf{'}s very similar to the previous slide except the trade has code
the DEF method the inside and the case class has override that def
method other than that it\textsf{'}s good could be case class just like in
the previous slide and again you see this class extends heads plus
with integer time from type parameter and not with an arbitrary type
parameter and this extends with a string not with arbitrary type parameter
so just as in the previous slide this defines a partial type 2 type
function and now this is a function that\textsf{'}s only defined for a certain
a for a either int or string so this code is quite similar to having
defined a function plus with a type parameter a having this type signature
except that a must be from this type domain it\textsf{'}s not quite the same
as having defined such a function directly because plus doesn't have
a type parameter and we can only access it by first creating a value
of this type and I'm doing that value dot plus so because it\textsf{'}s a def
method there must be the syntax value dot plus another limitation
is that all the functions support so we see this plus is one of the
partial type to value functions it\textsf{'}s a type to value function which
is defined only for certain types all of these must be defined up
front in the code of this trait so if I want plus minus times or divide
or whatever I have to define all of those as def methods up front
in this train I cannot later defined further partial type two value
functions here and also I cannot use this partial type two value function
in a different one defined later so that is quite a significant limitation
so this mechanism kind of works for implementing a partial type two
value function but it is limited so the object-oriented way it gives
us some leverage but it\textsf{'}s it\textsf{'}s limited we will be using this mechanism
in many cases but we need to have a more general mechanism for implementing
partial type two value functions so what is that mechanism to understand
this mechanism remember these values of type has plus of a here only
be of two different types as plus event or as possib stream there
are no other values that your code could possibly define so let\textsf{'}s
use that fact now there are only certain values that your code can
define and require these values to exist and in this way we will define
a partial type two value function so here\textsf{'}s how it works suppose we
want to define a function func with type argument a and some whatever
value arguments and we want to define this only for certain types
a first we define a partial type two type function that is defined
only for these types a so we do it in the same way here there\textsf{'}s really
only one way in Scala of doing this make a trait and make some classes
that extended with specific type parameters like this or like that
that\textsf{'}s it\textsf{'}s the same thing it just there\textsf{'}s only one way of doing this
in Scala so it first to create this partial type two type function
which defines your type domain its defined only for the specific types
you want let\textsf{'}s call this for now is good so it is this type parameter
good and if so then we can proceed with it we create some specific
values of these types for all relevant types a would create a specific
value so this would be to say we create a value of this type you have
to create a value of this type just you know Val a equals this without
B equals that and that\textsf{'}s what we will do now we will add an extra
argument to this function func in addition to all the arguments it
already has or needs we add another argument which we will call the
type evidence and this argument will be of type is good of a so this
function cannot be called unless you have a value of this type and
you can only have values of this type if the type is supported by
the partial type 2 type function in other words if the type is from
the correct type domain that you are defining it becomes now impossible
to call this function with an unsupported type parameter a because
you will never be able to produce this value type evidence here you
you can only produce values of these two types even if you define
the type for a different type argument you can produce the value of
that type so you could you could define a type of my TC of booing
but you will never be able to produce a value of that type and calling
func requires a value of that type so because we added an extra argument
to funk so the type evidence is that value that is required now with
a new argument that we have it and that guarantees we will always
call func value with correct types a trying to call with wrong types
will failed compile-time you can put some type evidence value for
the wrong type at the wrong type check so that\textsf{'}s a compile-time guarantee
now you can make the trait not sealed here it was sealed because we
were just thinking in terms of disjunctions but this trade doesn't
have to be a disjunction it\textsf{'}s just a type constructor it\textsf{'}s just a
type two type function and it doesn't have to be sealed these don't
have to be final case classes they could be actually traits themselves
or they could be objects or the case objects or they could be just
classes not case it could be anything it doesn't have to be a disjunction
we're not using this as a disjunction really we're using this as a
partial type to type function so the only thing we want to define
is a type and some values of that type with specific type parameters
how we do this is implementation detail one easy way of doing it is
by using traits and classes that extend the trait we will see in the
sample code another way of doing this or several other ways of doing
this that might or might not be convenient for different situations
let\textsf{'}s implementation detail the important thing is if we make this
a tree that\textsf{'}s not sealed we can add new values for new types later
so in in the libraries say we provide this with some standard types
in an application we want more types so we just add more values there\textsf{'}s
no need to modify the library code so that\textsf{'}s extensible new supported
types can be added in user code and that\textsf{'}s a great advantage so that
actually is the general solution of the problem of defining a partial
type two value function now the solution has its cost here is what
we have to do now first all calls to this function will now become
calls of this kind we have one more argument for each call this tantrum
you have to put one more argument now this value this evidence or
type evidence is the value that we need to create her each supported
type a so if you have 15 different types that we want to use need
to create 15 different values a lot of code and that code is probably
going to be very straightforward just automatic kind of code which
software engineers call boilerplate boring that is still missed it
needs to be written and finally all these evidence values have to
be passed around all the time because you call these functions in
different places in your code have to get these these type evidence
values you created created these values in one place but you have
to pass them all around your code whenever they're needed so that\textsf{'}s
a lot of extra work for if you want to use these functions many times
them in different places of your code that would be a lot of work
in Scala these issues can be mitigated and mechanism for mitigating
these issues is by using implicit values which we will look at very
soon then we look at specific code the result of using implicit values
is that type evidence arguments are only explicitly mentioned at the
declaration side of the function func and when you call it you don't
write them all so you don't have to pass them around they are already
passed around invisibly once they are defined as input set these type
evidence values and also you don't have to write a lot of code to
define type evidence values for all kinds of types because you can
define rules by which new implicit values can be built up automatically
from previously built up implicit values and the compiler will do
that recursively as much as necessary so that\textsf{'}s more or less solves
all these three issues however I would like to emphasize that these
are cosmetic issues which make make code better and easier to write
they do not change the character of the code in a qualitative way
these gains will stand whether we use this or not so we can use this
mechanism the partial type 2 type functions so in languages that did
not support implicit values we can even use this in Java these things
are just cosmetic issues with their positi of the code and it\textsf{'}s not
changing the fact that we have implemented partial type 2 value functions
in the most general way possible so what is the scholars mechanism
of implicit values so here\textsf{'}s how they work you declare a value of
some type as implicit and also there are implicit def methods and
implicit classes that you can define once you have defined it like
this you can start defining functions with implicit arguments so like
this for example and then once you have defined a value of this type
as implicit you can call this function by you're saying F of args
you don't have to pass X into it that would be found so the compiler
at compile time will search in the local scope for this definition
or in imports or in companion objects or in parent classes and it
will find a definition like this and it will substitute that value
silently and invisibly into your function so by the way having more
than two implicit values of the same type is a compile time here so
you cannot say implicit well X some type and possess well Y some type
next to it that would be a compile time here in addition to this Scala
has a short syntax for declaring type evidence arguments which is
which is specifically very useful for declaring partial type to value
functions and the syntax looks like this so it looks like you're saying
that type parameter a is itself of some type well it\textsf{'}s like a type
4 type notation but actually it\textsf{'}s completely equivalent to this code
take all these arguments that you have and add another list of arguments
which are all implicit and they will have automatically generated
names and the types will be this type constructor of a this type constructor
will be and so on so this code is just shorter easier to read and
this is longer but in exactly the same is less it it just rewritten
so you could have some arguments implicit written out like this some
other arguments written out like that we can combine both they will
be already written to one big list of implicit arguments at the end
so the difference between these two is that if you want to use the
evidence argument in the code of the function you need its name and
in this definition you have the name you define it yourself in this
definition you don't see that name so that name would be automatically
generated you don't see it don't matter another problem there\textsf{'}s a
special method defined in the standard library which covers a scope
which is called implicitly and that method can grab the implicit argument
defined for you when they define functions of the syntax the definition
of implicitly is very simple and you could have defined it yourself
it\textsf{'}s just defined for convenience for you in the standard library
we'll see how that works in one of the worst examples later so these
things make the code shorter we still need to declare the trait or
the type constructor as a partial type two type function and we still
need to create type of evidence values I am declaring them as implicit
but passing them around is very simple and calling the function is
much shorter because of the implicit mechanism so now having done
all this to let me say what typeclasses are so right now we were talking
about partial type two value functions and partial type two type functions
but this is not really the terminology that most people use it is
just the terminology that I find the most illuminating it tells you
exactly what we're doing but actually people say typeclass what sorts
a tight class a typeclass is basically a set of partial type two value
functions that all have the same time dummy which means that for example
you can have plus minus times divide let\textsf{'}s say and they all have the
same type domain which is numbers that can be added subtracted divided
in something so instead of saying typeclass we could say some partial
type two value functions that somebody has defined that\textsf{'}s the same
thing so in terms of specific code that needs to be written the typeclass
is two things first it\textsf{'}s a partial type two type function so it\textsf{'}s
a type constructor with some code that creates specific type evidence
values of specific types T and that defines the type domain second
it is the code for the desired PT lives so whatever functions you
need to define your write code for them and you use that PT TF in
that code to define the type domain also for many important use cases
these functions must satisfy certain laws certain equations for mathematical
reasons otherwise it would be unusable or programs will have difficult
bugs so that\textsf{'}s what typeclasses are that\textsf{'}s a definition of a tag class
let\textsf{'}s fix some terminology people say that a type T belongs to the
typeclass my tag class what does it mean it means that there is a
PTT F partial type two type function called the called this and this
partial type of tag function has a domain to which type T belongs
so for example integer could be T and then integer belongs to this
if that type domain includes the integer which means that there is
a type value sorry type evidence value of type MyType plus int so
if some value of this type can be found then the type belongs to the
type cost that\textsf{'}s what what it means when people say that now a function
with type parameter requires for this type parameter the typeclass
might a class what does it mean well it means that actually one of
the arguments of this function usually implicit argument is the value
of a type like this which is constructed using a partial type two
type function so if you if you see that there is some partial time
to time function lying around then you know that this is a partial
type 2 value function that requires F typeclass constraint or it constrains
a type parameter to belong to the typeclass otherwise it cannot be
called with that type now another important terminology is that the
evidence value the type evidence value which is this extra argument
of this type that value itself is is called not only type evidence
is also called the typeclass instance now that terminology is completely
equivalent to type evidence so I prefer evidence but instance is also
standard terminology I will explain how how to create these things
in many examples now so typically in Scala you create a trait with
a type parameter like this then you create code that makes values
of this type for various types T all these values are declared as
implicit and somehow you make them available for user code either
while imports or put them into companion objects for the types T which
is quite convenient because then you don't need any imports then you
also write some functions not have implicit arguments of this type
usually these metals are def methods these functions are def methods
in this trait we don't have to be but often they are because that\textsf{'}s
sometimes necessary and often convenient so as a rule a type evidence
value should carry all the information they need about the typed you
will see why let\textsf{'}s look at the examples so semigroup is a typeclass
that actually let me show you what it is a typeclass that has an associative
binary operation so in other words there must be this function which
is a partial type 2 value function it takes two arguments of type
T and returns a value of type T so it\textsf{'}s a any kind of combined operation
so combine two elements and get another element of the same type combine
two values in any way as whatsoever as long as it\textsf{'}s associative so
it doesn't have to be commutative doesn't have to be any inverse operation
to this just can combine two values into one larger value in some
way doesn't even have to be larger value we don't know anything about
how it works so that\textsf{'}s semigroup it\textsf{'}s a very weak very bare-bones
kind of operation binary operation it just is associative that\textsf{'}s the
only thing we know so let\textsf{'}s implement that operation is a partial
type to value function first step is to implement PDGF so let\textsf{'}s just
do that semi group with parameter T then we have two K subjects let\textsf{'}s
say well we have semi group and semi group string that\textsf{'}s all nothing
else fine so that actually defines PTT F that defines a type constructor
of which you can only have value semigroup event and semigroup of
string so that\textsf{'}s sufficient in principle to create our partial target
value function so let\textsf{'}s see how we can do this so we can define up
here the type parameter T it has an x and y as required it returns
the t as required it also has an implicit argument which is the type
evidence of type semigroup t so now this is it this is the partial
type T value function you could not call this function with a type
parameter T for which you cannot have cannot have a value of semigroup
T so you could not call this with type parameter T other than int
instance so this test for example says you can combine ends you can
combine strings but option event cannot be combined this doesn't even
compile because the type option int is not within the type domain
of this partial type function and so you cannot have any type evidence
for it and so it just won't compile so that\textsf{'}s great now how do we
implement this function well we have to add somehow integers or strings
but how do you know which is which so let\textsf{'}s see this evidence is the
argument so the only thing we know about type T is this evidence value
so we can imagine it where two cases so it could be an int or it could
be a string evidence so if it\textsf{'}s an int evidence we know that T is
actually int so well what can we do well the only thing we can do
with the force X to be event Y to be event add them together and then
force their is out to be again of T because we're supposed to return
T and that\textsf{'}s what we have to do and we have to do we can do the same
for string and actually this code works as the test shows the test
passes it\textsf{'}s a very unsafe code is not great not not not great at all
because of these as instance of operations which are unsafe and maintaining
this code is very hard and so don't do that we will never do this
I'm just showing you an example of how we could do it in some way
and that actually is an implementation of a typeclass so semigroup
is a typeclass up rather op is a type course is a partial type to
value function with a type domain we defined and it works for that
type domain that\textsf{'}s that\textsf{'}s the typeclass a semigroup we have implemented
seven rules on very ugly but we'll do it much better in just a few
minutes this is our very first example note we derived the requirements
for this completely systematical there is no there\textsf{'}s no guessing so
we must have a type dummy we must have a type function type constructor
and we must have the implicit evidence argument well implicit is just
convenient so we don't have to write this argument here in principle
we could so the OP function if you look at it it has the second of
arguments which is this one their evidence and we could put this evidence
here in parentheses for example sending group into evidence it\textsf{'}s exactly
the same so this is how the function actually must be called and the
compiler writes that for us we don't have to write that in our code
so that just makes our cold sugar other than that that\textsf{'}s what\textsf{'}s going
on this all right now why is it that we had all this trouble it\textsf{'}s
because we have no idea what tedious we know that it\textsf{'}s either int
or string so in this case it is int in this case it\textsf{'}s string but we
don't have any functions that help us to work with that so the way
to solve this is to put more information into the evidence so right
now here evidence is just an empty object it has no information except
the type we put more information into the evidence we can get it out
and work on these x and y\textsf{'}s so why don't we just put the implementation
into the evidence instead of putting it here and having all this trouble
with type custom so that\textsf{'}s what we do next we again implement semigroup
again for empty string now the partial type to type function in our
case is not going to be a sealed straight it\textsf{'}s just going to be a
type function which we define and it\textsf{'}s going to carry this data so
actually you see what we need is to combine these to fund these two
elements and that\textsf{'}s very natural to put that information directly
onto the type constructor so now it\textsf{'}s very easy for us to do find
the evidence values so we just say this function which is adding two
integers has this type and that\textsf{'}s correct this function has this type
that\textsf{'}s correct so we have defined values of type semi group in the
semi group string so that together with the type function defines
a partial type two type function so now semi group int and semi group
string are defined and others are not defined we put them as implicit
now we define the partial type two value function let\textsf{'}s say we define
a sum that\textsf{'}s what we wanted there is a sequence of values T and there\textsf{'}s
a default value for empty sequences say then there is an implicit
type evidence argument so now the implementation is actually very
easy we just do a fold left with the default element as the initial
value and the fold has a function argument which is this OP an evidence
has exactly the right type it is the hope so we just put it in there
and we're done with no typecasting completely typesafe implementation
and yet this is a partial type 2 value function because it can only
be called on integer instrum and this is a test that shows how it
works so this is a minimum implementation very very bare-bones implementation
of a typeclass which is the sum a semigroup is the type 2 type function
and sum is the type 2 value function we can define further type to
value function functions if we want to use them this type 2 type function
so that\textsf{'}s a second attempt at defining a typeclass and the code is
very easy as you see now let\textsf{'}s try to use traits instead now this
is a third implementation of second group we put this method which
used to be here we put it as a def mounted on the trade so we override
this then in the two specific implementations for integer and string
evidence so that defines our PTT F and just as in the previous example
all the data it\textsf{'}s necessary for implementing what we want is carried
by values of this type so all the data is carried by values of this
straight now we do implicit case object just so that we don't have
to write more implicit Val\textsf{'}s in principle what we could do is we could
say for example here is taste object not imported and then we said
well maybe C equals that equals singing group in evidence we could
do this just as well it\textsf{'}s just shorter to write implicit case object
right here so we have defined a PTT after now we define a PTV F which
is adding of three numbers let\textsf{'}s say and we define it in the same
way so we have arguments at once and then additionally an implicit
evidence argument and then we use the evidence dot up to perform the
computation we see evidence dot what is this op that has been defined
in the trade and since it\textsf{'}s a deft method on the trade we have to
use it in the syntax F dot op whereas here we didn't so here we could
define add three C we can define new PTV F very easily so this must
be of type same in Group G so how do we do that we do F F is a function
right so that type is this function so we just do have of X or Y Z
for example random so we can define any number of DVF\textsf{'}s externally
user code just like what we wanted so that\textsf{'}s exactly how we expect
this to work and here instead of saying just F will you have dot off
every time because here op is a death metal in your trait same things
should work alright so as we have seen it is quite useful if the type
evidence value carries all information but the ETF\textsf{'}s need to know
about the type team and in many cases the trait contains these materials
directly in some simple cases it can be a data type not a trait but
actually as we will see a treatable death metals is necessary if we
need higher order type functions it is convenient it\textsf{'}s not particularly
inconvenient to heaven it\textsf{'}s just more writing to do trade with death
metals if you can avoid it you don't have to do it and as we just
have seen additional partial type 2 value functions using the same
unchanged type 2 type function can be added later so no need to modify
the code of this trade if we want to add new partial type 2 value
functions without changing the type domain so add 3 as an example
we don't change the type deleting some and add 3 are defined for the
same type domain for things that can be added no need to modify the
code of library if we want to add more partial type 2 value functions
with the same type domain and as we'll see later we can combine this
with other partial type functions that we define in other code so
that\textsf{'}s exactly what we wanted let\textsf{'}s look at some more examples of
typeclasses semigroup we just saw now another interesting typeclass
is pointed it\textsf{'}s a very simple time code typeclass it just has a function
point that returns a value of that type so that means somehow there
is a special and naturally selected value of that type and the function
gives you that value examples would be 0 integer type or empty string
so these are naturally selected values of the type or for a function
type it will be the identity fun for this function type that\textsf{'}s also
naturally selected value so I mean it\textsf{'}s still selected in a sense
that somebody selected it it\textsf{'}s just that it\textsf{'}s natural to consider
that value it\textsf{'}s useful to to have some kind of value of this sort
and maybe it will have interesting properties and so if you have a
value like this then the type is pointed an example of a type that\textsf{'}s
not pointed is a function from A to B there\textsf{'}s no way to have some
kind of natural function from A to B but from a to a there is you
have the identity function another important typeclass is Mohammed
monoid is a typeclass that represents data aggregation so data aggregation
means you have some aggregator that is initially empty and you put
data into it and it combines everything you put it into it into some
aggregate value so it has two functions empty and combined so empty
is just like the point it just gives you the value of that type and
combined is just like the semigroup takes two values of the type of
returns one additionally though we require that combine is associative
just like in a semigroup and this law must hold so the empty value
combined with anything either to the left or to the right should again
return the same anything that you passed in so combining an empty
with X does not change X that is a requirement so the value of the
empty aggregate is special in the sense that you can combine empty
aggregate with data and that doesn't change that data so monoids are
used a lot in different contexts so one obvious context is log aggregation
so you add logs and it\textsf{'}s still log so you can add more you know put
two logs together still it\textsf{'}s a bigger log but it\textsf{'}s still a log so
that\textsf{'}s you know you have an empty log or you can combine two logs
that are maybe empty and you still have a big log as a result so logging
is one application of this and there are other applications many many
other occasion so one know it is a is a very useful abstraction so
now we'll see examples of how to implement the monoi typeclass by
either just doing it from scratch sorry implementing the PT TF and
so on or in a very interesting way if we assume pointed and semigroup
first so so pointed typeclass has this point function seven group
has the OP function and you know it has these two functions of the
same types while the names of the functions are completely material
of course they can rename all you want the types are important so
types are the same and so monoid is basically a semigroup combining
is pointed and we can write code exactly saying that and save us the
trouble of implementing everything from scratch so now we'll see how
that works so first let\textsf{'}s implement monoid from scratch we will not
use trades will not use any names just the bare-bones implementation
so the idea of implementation is that first we do a partial type 2
type functions so we define a type function and the value of this
type should carry all the information we need to know this information
consists of two pieces first the empty value remember the specification
of monoid we need an empty value and we need a combined so empty value
is just T combine as a function from T and T 2 T so let\textsf{'}s put these
two values in the tuple so we'll have a tuple of T and a function
from T and T 2 T that\textsf{'}s good enough we don't really need any names
or trades or anything we just need the data the fact that they are
called empty or combined this fact is immaterial this is not important
we can rename this you can call us zero instead of empty we can call
this append instead of combined or add or whatever or op it doesn't
really matter what matters is the types so let\textsf{'}s define the type domain
for this partial type function that means we defined implicitly of
type monoid int and 108 string so we define these values these are
the tuples having the selected int value and the function that combines
integers and the selected string value and the function that combines
strings let\textsf{'}s do it this way done so now we have the partial type
2 type function defined now let\textsf{'}s define the function sum well we
have finished defining the monoid typeclass let\textsf{'}s define some partial
functions so the function sum will take an argument of sequence of
T and T will be constrained to have a monoid instance so or to have
an evidence of belonging to the monoid typeclass so how do we do the
implementation while we fold down the sequence the first argument
of the fold is the initial value which is the first element of the
tuple the second argument of the fold is the combining function which
is the second element of the tuple that\textsf{'}s it we're done so some is
implemented and it works let\textsf{'}s implement a monoid tie plus in a slightly
more verbose manner which might be not bad because it documents what
we're doing it also helps read the code later because this code looks
a bit cryptic with T comma T comma T parenthesis it\textsf{'}s a bit cryptic
so let\textsf{'}s define names so instead of just using a tuple let\textsf{'}s use names
to pull name to post the case class so let\textsf{'}s use it in case close
call it monoid put names empty combined so exactly the same type and
we define a type function in exactly the same way except now has names
and these names help to help us document what we're doing exactly
the same definition of the time to type domain except with the name
exactly the same definition of the function some except now we have
F dot empty and F dot combined because the typeclass has names if
you compare with the previous definition that was f dot underscore
one F dot underscore two so evidence now is a case closed and we can
use noise names that\textsf{'}s exactly the same code now good let\textsf{'}s look at
defining the pointed and the seven group in the same way so we define
it as case classes with so this is the partial type two type function
with its domain this is another partial type two type function with
its domain now this is the partial type two type function we want
to define and we want to automatically derive we don't want to repeat
implicit values at all here how do we do that we use this with we
use this implicit death so blessed F is a scholar feature which is
that this function will be called by the compiler whenever necessary
if it needs to produce an implicit value of this type it will see
if it can call this function and if implicit value of these types
are available if so it will insert the code to call this function
and create these this value and put that into your implicit argument
all of this will be happening silently and invisible so we define
the instance is a function with two implicit arguments which returns
the type evidence so it takes type evidence for semigroup and type
evidence for pointed and returns type evidence from unalloyed well
how do we do that well the type evidence from a Lloyd is a value of
this type so we need to just create a case class value of this sorry
of this type so we just say monoid which creates a case class value
and we need to provide it with two values with the empty and that
is the point from the pointed evidence and the combined function which
is the cop from the sum of your packages that\textsf{'}s it so we have defined
the monoid instance the test will show that it works so we have not
defined two different monoid instances for in ten string nevertheless
we can use int and string in our code because this implicit def will
generate them so imagine here we have 15 different types it\textsf{'}s a big
savings in code that we can automatically your life cause instances
typeclass instances from previously defined evidence values now one
other thing I'd like to show is that all these things are actually
already defined in the library called cats and also in another library
called scholar Z so all these typeclasses are pretty standard the
semigroup the maloik and so on and they're defined in these libraries
and the difference between these libraries may be names because types
are the same your standard mathematical structures but the names might
be different so in the cats library the names are empty and combined
in the scholars e-library they're different names types are the same
so how do we use the library to define Illinois so here\textsf{'}s a here\textsf{'}s
a test so we want to say that if we have a semigroup and we have appointed
we want to define a cation or instance so then we do it like this
we define a value of type Katzman on it and that\textsf{'}s a class so we do
a new and then we override the functions empty and combine now unlike
what we did here the cat\textsf{'}s library does not use keys classes it uses
traits and death methods so it means you need to override things but
that\textsf{'}s how it is otherwise it\textsf{'}s exactly the same thing and then we
can define some for the cats monoid and we can do the same test as
before now one another thing that is interesting is that we can check
laws in a generic way so I implemented this function to check cats
monoid laws which is a function with a type parameter that takes an
evidence that M is is from the cat monoid typeclass so these things
are necessary for law checking all these assertions and arbitrary
either property checks library notice I'm combining all kinds of syntax
here I have typeclass syntax like this I have implicit argument of
another type cost like this it\textsf{'}s completely up to me and so this function
will check their left and right identity laws that combine of empty
and M is equal to M combined of M and M T is equal to M when the function
data is equal is a general way of comparing two elements of type M
it might be non-trivial if M our function types so that\textsf{'}s why I have
this data is equal by definite by default this is just a comparison
but it could be different for function types we'll see examples for
this social tivity law also needs to be checked up for all ABC and
combine a combined BC is equal to combined combined ABC so that\textsf{'}s
associated and then I can call this function for interest ring but
that won't compile because we didn't define them an audience in school
double isn't a side here\textsf{'}s how we can check laws for the partial type
two value functions in a typeclass I'm using the Scala check library
and the typeclasses it uses itself for instance or the arbitrary typeclass
that typeclass means that the type has a function that produces arbitrary
values of it or some set of values and that allows me to write for
all function but of course cannot check all possible values but it
checks the large number of them so then I write a function like this
which is a generic function taking any type T as long as this type
has an arbitrary instance and also a semigroup instance and then I'm
imposing the condition that for all X Y \& Z of type T the operation
is associative so the operation of X with Y Z and gives me the same
result as first combining x and y and then combining that result with
Z now see I could have rewritten this function in a different way
in a different syntax like this I can combine the typeclass connotations
and this is just a different syntax and then I don't need to write
this however now I need to replace this with something I need to access
this operation which is the partial type 2 value function in the semigroup
typeclass previously I had an implicit argument with named semi group
F now the name is hidden I don't know what that name is so instead
of doing this I just say implicitly same in group t that\textsf{'}s and that\textsf{'}s
exactly the same thing so implicitly fetches the value of the pro
of the implicit parameter of the given type and there\textsf{'}s only one because
there is a compile time error if they were two different implicit
values of the same type so that\textsf{'}s how I would write the code if I
didn't want to put an explicit argument argument but actually it\textsf{'}s
exactly the same function that if I look at this function here I use
it in exactly the same way I don't call it with any arguments so this
is just syntax I can use this syntax or I can use the syntax I had
before so once I have defined this function I call it by substituting
different type parameters and this itself is also a partial type to
value function that takes a type parameter and returns an assertion
value and that better be success if it\textsf{'}s a failure the test would
fail so that\textsf{'}s the way I can use the the Scala check library to test
laws similarly I have a function that tests the monoid laws it takes
an annoyed evidence and then tells me that there is a combined with
empty which returns me the same value so notice this function is defined
separately from the typeclass but it uses the same type domain as
a time code typeclass it does not change the monoid or arbitrary type
domain so I can combine two different type domains so there\textsf{'}s no problem
in defining partial type two value functions later in the code without
changing the code of monoid typeclass later I can define further partial
type two value functions like this one which will work on any type
belonging to the relevant typeclass so that\textsf{'}s the kind of extensibility
we wanted use that to make my tests that verify with my defined instances
for the moon the weight of integer in the noid of string they satisfy
the correct mathematical law laws here\textsf{'}s an example when this does
not happen it does not satisfy the laws I create an instance of semigroup
for a boolean but I use the operation which is the boolean implication
if X than Y now this operation is not associative if I define this
as my semigroup evidence which is the same as to say if I define this
as my typeclass instance for boolean of semigroup typeclass then my
law will not be satisfied so the associativity law is not going to
be satisfied when I call this function this test will fail and it
will print a counter example let me run this actually the Scala check
library is such that it doesn't just check the laws for a large number
of values of the parameters but if it finds some values that do not
satisfy the law it tells me what those values are it will print the
counter example values and then I can write a test where I can debug
to see if this was about to see why it did not satisfy the law or
I can write a test and that will correctly pass the law so let me
just wait until this compiles there\textsf{'}s a number of things it needs
to be it needs to do and wellness test runs yeah so it fails it says
true did not Eagle falls the current past generated values false false
false so it prints a counter example in the previous run I had a different
counter example which is false true false but false false cause apparently
is also a counter example so then I have a test here that verifies
that the laws are not holding and I use again this implicitly just
to fetch in this but I could just instead of this since I know what
that evidence is I can just say that the bad sending your evidence
with exactly the same thing that\textsf{'}s to say I made I declare that as
implicit so fetching the implicit of this type is the same as just
using your value of the type so now tests pass so let me undo my change
alright so now let\textsf{'}s consider a different example of typeclass which
is a typeclass for a type instructor the example is that of a factor
so the type constructor is a function if it has a map operation equivalently
in earth map that satisfies the function laws which were they had
identity law in the composition law now we would like to write a generic
function that tests the functor laws so this function would look like
this it will take the type constructor as as well as three types say
ABC has type parameters and it will then run the tests with various
values and check that all the laws hold for this type constructor
this generic function should require that the type constructor F be
a factor and we need to also access the function map that is defined
for the given type constructor F so therefore we say that the map
must be a typeclass so it is a partial type to value function whose
type domain is following the filter type constructors while the factors
F that we have declared and then we constrain F to belong to that
typeclass in this function unit check frontier laws where did we do
this in exactly the same way as before the only difference is that
the type construction now is of a different kind is a type parameter
F is a type constructor and not just a type based type nevertheless
we just declare a partial type 2 type function called factor which
will be called like this it\textsf{'}s type parameter is this F which is this
type constructor and this will be well defined only for type constructors
F which we have defined a functor instance in other words will define
this implicit evidence value for each functor instance and we will
then require that this implicit argument be one of the arguments of
the check functor loss function we will see the implementation in
a second and for now just note that functor is a higher-order type
two type function it\textsf{'}s a function whose argument it\textsf{'}s a type function
but it\textsf{'}s argument is a itself a type function whose effort self the
type function so just as we do with ordinary functions and we say
that a function whose argument is itself the function is a higher-order
function so here we just say this is a higher-order type function
because it\textsf{'}s argument is a type function it\textsf{'}s already let\textsf{'}s look at
the test code them so we proceed in exactly the same way if you want
to implement the Thunderer typeclass there\textsf{'}s no matter that it\textsf{'}s a
higher-order type function we do exactly the same thing we define
a trait let\textsf{'}s say with a type rounder which is this F and we need
to use the syntax with square brackets and underscore to show that
this type is itself a typed function so this type parameter is itself
a type function the trade has this def method which has itself to
further type parameters because the factors map function has this
type round now having these two type parameters pretty much forces
us to use the trait with the DEF method for implementing the partial
type two type function we could not do this within a data type because
in Scala data values cannot have it themselves type parameters only
def methods can have type parameters there are some ways of circumventing
this limitation but they do not significantly change this fact they're
just hiding the fact that somewhere there is a definite end with type
parameters so let\textsf{'}s not try hide this fact but use the trade with
definite as very necessary so this is a partial type two type function
what what is its type domain what are the type constructors for which
we can have some values of type funky of F well let\textsf{'}s say data one
is one such type constructor so let\textsf{'}s define some type constructor
like this simple one let\textsf{'}s define the evidence that this type constructor
belongs to the type domain of this type function so the evidence means
that we create a value of type filter of data 1 and this value could
be anything could be evolved it could be an object so one way to write
it is to say implicit object another way would be to say implicit
well and then to say new here it\textsf{'}s another different way of doing
the same thing which one is better it\textsf{'}s not so clear right now let\textsf{'}s
just use one of them now in this value when we extend this trait with
a specific value of the typewriter we need to override this death
metal because this def method has a different implementation for each
type for each type constructor here so we need to override it so here
we just write the implementation of the f map for the data 1 constructor
so we already know how to do these things and I will not dwell on
how to implement the factor instance for case closed now this is this
is the entire definition of the partial function for type 2 type it
now let\textsf{'}s define our type 2 value function the map will use the F
map will define generically the map so how do we do that well the
F is one type parameter and we say this must be a functor that close
and alb are two other type parameters and we define the F map as the
functors F map so we fetch the implicit value which is this value
or take the F map of it which is this sniff method apply distill F
we get F of A to F of B and then apply this function to F a this gives
us a value of f of B and that\textsf{'}s the map method so the map method basically
by hand we just use the F map and call it first of F and then on data
and one away but you see this implementation is generic for all factors
it is not specific to data one so in this way we have defined a generic
partial type 2 value function where the type constructor is constrained
to be a factor this is exactly what we wanted it would be impossible
to call this with a type parameter that is not a factor because there
is the implicit requirement so it required implicit argument it wouldn't
be available other words so let\textsf{'}s see how to use this so okay so we
have this map function how do we use it let\textsf{'}s create some data of
this type and we just call that function on that date just an ordinary
function the fact that this is a partial function is transparent we
don't have to say what the type is the types are infrared data has
a specific type data one of int this is a specific function from integer
string so we transform this and we get data one with values one a
B C 2 a B C or D 2 this transformation the result is of type data
one of string so that\textsf{'}s a typical result of applying a santur to data
so as you see using the function map is no different from using a
loan generic function but the definition of map is a generic one it
would not have to be extended if we have more data types like data
to that\textsf{'}s safe with another function instance won't have to extend
this function so this is very good for library design because we can
put these functions into the library and we'll never have to extend
them it\textsf{'}s only the users code that needs to extend this needs to declare
functor instances for new data types but this has to be done once
together with each data type and you're done here\textsf{'}s a function that
can check functor laws it\textsf{'}s a bit involved because functor laws involve
arbitrary functions from A to B and from B to C and so I explicitly
write down all the arguments that I need so these are the implicit
arguments of this function factor f is a typeclass for functor then
there are these arbitrary instances of typeclass so the Scala check
library needs to use arbitrary values of these types to run the checks
and if I don't put them here that it doesn't know that they exist
but finally when I use this function I just give it some specific
types and I don't have to specify anything more than that all these
arbitrary instances are implicit values that are defined in the library
and I don't want to talk about them in my code so for library design
this is great the library becomes much more powerful and know his
record needs to be written so just to be sure this is clear what this
is doing it\textsf{'}s checking the factory laws for specific types so data
one is a factor and for example a the type parameter a here is int
so here the identity law will be only checked for the int type so
that into the int identity on data one instances of type data one
int are preserved after F map that\textsf{'}s the only thing that can it will
check now I can obviously add some more checking here with different
types with other types it\textsf{'}s up to me I I can do this or I can neglect
doing this but no more no necessary extra code so so let us see how
the same works with a cat slightly you know the cats library has a
standard function typeclass which is the cats not funky it works in
a very different way except that it uses makeup rather than death
map so the order of arguments is that first there is the data or the
functor and then there is a function whereas the f map has the opposite
order first the function and then the data now a convention that I
follow is that the implicit values should be in the companion object
of the data type now this is a useful convention because Scala has
a mechanism for searching for implicit values and it will search in
the companion objects of the types you are using so there is some
function that tries to find implicit value of functor theta1 the compiler
will automatically search in the companion objects of function and
in the companion object of later one now it makes sense to put data
one specific stuff in a companion object of data one and functor specific
stuff into a companion objective factor the factor is in the library
later one is my own code so that\textsf{'}s why I first defined my data 1 as
as my own custom type and then I define companion object which is
in Scala just an object with the same name as the type it\textsf{'}s a special
convention in Scala so in this object I have my implicit value I can
again I can do implicit Val and then equals new if I want or I can
do implicit object extends this it\textsf{'}s up to me there is not a big difference
and not a very different amount of code to be written when I write
the implementation of the function instance so I implementing lab
and then I check the factor laws so this function is very similar
to what we saw above except it uses the cat\textsf{'}s function typeclass within
map so that\textsf{'}s implemented in my test code very similar code checks
the identity law in the composition law given three arbitrary types
and a type constructor that must be effective so now having seen this
let us take an overview of what we have achieved we have been working
with type 2 value functions and type 2 type functions let\textsf{'}s compare
value to value functions and type 2 value functions now value to value
functions as the ones that are the ordinary functions the domain of
a value to value function is the set of its admissible argument values
we call that a type so the type is the subset of values that are admissible
as an argument of functions of for example if the function takes an
integer type of the argument when strings are not admissible arrays
of something are not admissible nothing else except integers are admissible
so in the set of all integer values is the value domain of that function
and that\textsf{'}s what we call a type so the function can be applied safely
only if the argument is of the correct type and this is the example
of having a function we declare its type and then we apply to some
Y value and unless Y has this type this is not safe to do so so not
safe to apply and if Y is not of this type there will be a compile
time error that\textsf{'}s how we use types types prevent applying functions
to incorrect arguments now let\textsf{'}s look at the partial type 2 value
function it has a type domain which is the set of admissible argument
types or type parameters the type domain is a sub set of types a sub
set of type parameters that the function can accept so that is actually
called a kind this is terminology it is accepted in functional programming
so we say that the type 2 value function can be applied only to type
arguments of the right kind similarly to a value to value function
that can be only applied safely if the argument values are of the
right type a function like this where we declare it\textsf{'}s type parameter
constrained to be in some typeclass this can be safely applied to
a type parameter a only if a belongs to this typeclass we say only
if alias of the right kind and in both cases the error will be caught
at a compile time so if this is not the right type if this type does
not belong to this typeclass writing this code will not compile in
the case of PT BFS that will happen because the implicit argument
will not be found but no matter it will still be a compile time error
so kinds are the type system for types values are of the right type
type arguments are of the right kind so a typeclass such as my typeclass
defines a new a new kind as a subset of types there is a type notation
which we use and there\textsf{'}s also a kind notation now the kind notation
is not part of the Scala language but we need a notation over the
last to talk about kinds so I suggest to use this notation so star
is a standard kind notation for any type basic type like integer or
string an actual type that has values so star is a type that has values
any type that has values and if I denote it like this with a typeclass
a notation that means I'm only considering types that belong to the
typeclass another existing available kind is a type function kind
notation for that is this so let\textsf{'}s look at an example consider this
type and here F and T are types of different kinds F is a type constructor
T is a type basic type not a type constructor so F is a type constructor
or type function and so f has this kind is a function kind which is
similar to function type except for types so it takes a type and returns
a type a kind of T is the star T is just a basic type the kind of
F is the function from basic type to basic type so this is the kind
notation star means the basic type error means a function and colon
with typeclass I suggest to use that for typeclasses here\textsf{'}s an example
we can define a type like this this is a type this is also type but
this is a type function this is also type function so the kind of
this is actually this expression it has two arguments the first argument
is a type function which is this kind the second argument is a basic
type which is a star kind and the return of this type function is
a basic type which is a star called a return is a basic type pretty
much always and so that would be the kind notation for app if I define
the up like this note that Scala compiler will not compile if I put
our own kinds so for example if I put up with two type parameters
but a and B but a is not a type constructor so the kind of a must
be the function kind or the type function kind if this is not so the
Scala compiler will given there let\textsf{'}s look at the test code so here
I define type function just any type function here I define the app
as in the slide now if I define type X like this I'm applying the
type function app to the arguments G and int G is itself a type function
defined here and so that\textsf{'}s okay because app has the right kinds of
arguments here so after I apply this X becomes the result of applying
G to int which is this that\textsf{'}s verified of X indeed is this so let\textsf{'}s
say X of type X is left of that and that compiles now if I were to
try writing code like this it won't type check because the kinds are
wrong the first argument of F must be a type function but it is not
it is a basic type similarly here the second argument of app must
be a basic type but it is not it is a type function so neither of
these two will type check let\textsf{'}s look at a little more complicated
example we will write the tag current notation explicitly here again
first we define a type constructor then we define app which has two
arguments and the kind of app is this and we can write more verbose
Li with argument names if we wish so f has the kind start to start
a has the kind star so actually Scala requires the syntax that shows
the kind you cannot just say F comma a if you write out of F comma
a it will assume that F has star kind so you have to write this syntax
if you want a higher kind higher order type now let me just say the
terminology in functional programming has higher kind of types I don't
think it\textsf{'}s very limiting types are types are not kind it we don't
say it\textsf{'}s a higher type function we say higher order function because
it\textsf{'}s a function that takes functions as arguments here we have functions
of types that take other functions of types of arguments why should
we call it anything else than higher-order type function or higher-order
type higher kind it is not very illuminating here so here is another
different where I define up with two peas which is three parameter
function the first parameter is itself a higher-order type function
of the same kind as app so I can express it like this in Scala it\textsf{'}s
a little harder to read I have two arguments the first argument is
a type constructor the second argument is a basic type and the function
P is a type function of these two arguments so the kind of P is this
the kind of Q is this and the kind of R is this basic typing so then
I can define this you see I'm applying when I define the type function
I said I need to apply P to Q and R and so Q is of the right kind
to be put into P so now I can say define X the same X that I had here
defined like this F by G int I can say app of app G and it will be
exactly the same thing I verified the same things as I verified before
namely that putting arguments of the wrong kinds does not work now
there\textsf{'}s one other thing that we would have to do if we want to be
completely free dealing with type functions remember that in functional
programming it\textsf{'}s important to have anonymous functions not just named
functions anonymous functions enable a lot of freedom in programming
and without them things are difficult so functional programming really
wouldn't work well without anonymous functions quite similarly we
need anonymous type functions until now all we've seen were named
typed functions all these names but we want also anonymous type functions
because without them things are just not always possible to express
anonymous type functions are more difficult to write in Scala but
it is possible to write and there is a compiler plugin that makes
the syntax easier it\textsf{'}s just the syntax plug-in and I use that plug-in
which is available and this address it\textsf{'}s called the kind projector
plug-in so let me show you how it works I define a type function just
a simple one and I define the app just as before now I want to define
a type function higher-order type function that takes a type constructor
and applies it twice to its type argument so app two should take a
P and the Q and then it will put Q twice into P so to speak so you
see the first argument of P is a type constructor now previously I
put Q as the first argument but now I want to put Q twice and on the
SEC U of Q of a type argument to express this I need an anonymous
type function because I want to put that anonymous type function as
the first argument of the type function P unless I have that I cannot
express this behavior this is the syntax of the kind projector it
has the special single lambda and then it allows me to write my anonymous
type function like this where X is now a new type variable anonymous
functions type variable so this is a very similar syntax except under
lambda and that is what the kind projector provides now instead of
lambda I can write instead of the Greek letter lambda I can write
lambda in Latin alphabet like that which is just more verbose no difference
so this app to has this kind it\textsf{'}s the same kind of app from the previous
example except that here it instead of using Q once it uses Q twice
it\textsf{'}s it composes Q with itself q is a type function it composes that
type function with itself in order to express such behavior we need
anonymous type functions so now if I apply this app to using the o2
type constructor which is just an option of a tuple a a then this
option of a tuple will be applied to itself twice so it will become
option of a tuple of option of tuple option of tuple and indeed that\textsf{'}s
what it is x2 has this type and type checks so this is a bit of an
advanced topic the anonymous type functions but this is similar to
anonymous functions so just the syntax has to be a little different
so as a result of this we have a uniform view of values and types
types are two values as kinds are two types typeclasses are just a
certain sort of kind function current type function is another sort
of kind so there are different kinds there\textsf{'}s type function kinds and
typeclass kinds and you can combine them you can have a typeclass
for type functions which is for instance for the factor factor is
a type function and we can have a typeclass for it you can of course
have typeclasses for higher order types as well so the syntax becomes
a bit more involved but you can still do it if there is a use case
for it so I showed you that there are some use cases for all these
generic functions main idea being that you want to save your code
you want to implementing generically right code once and have it work
for all factors for all types from a certain typeclass and another
thing that Scala provides by way of convenience is the implicit method
syntax so let me show you what that is this is very often used together
with typeclasses but this is a purely syntactic convenience there\textsf{'}s
no more power that this brings us the partial type 2 value functions
are exactly the same as before all of these implicit things are just
syntactic conveniences that make code shorter the basic idea of partial
type T value functions remains the same so here is how it works in
Scala in principle there are two sorts of syntax available for functions
the first is the syntax similar to that of the ordinary mathematics
where you say function name in parentheses you list the arguments
Scala also allows you several lists or one or more lists of arguments
another way is to have a syntax like this X dot func of Y which is
the method kind of syntax like object-oriented method all pretty much
object-oriented languages use this syntax in Scala there is another
equivalent syntax whenever you can say X dot funk of Y you can also
say X space funk space Y sometimes that\textsf{'}s easier to read now these
functions are similar but they're just implemented differently and
in some cases you can put you might prefer one in another case another
so here\textsf{'}s an example when it is convenient to have the method like
syntax imagine we define a function called plus plus plus it is a
partial type two value function and the type domain for it is this
typeclass has plus plus plus and then there are some arguments and
one argument is of type T so you will have to call this function like
this plus plus plus of T and art now you would like to write this
instead this is much more readable T plus plus plus Arg whatever plus
plus plus means in your application this is certainly easier to read
than this Scala provides a way of implementing that syntax this is
what I call the implicit method syntax extension syntax so what is
the implicit method syntax suppose you want to convert func which
is a partial type to value function to the syntax you declare that
as a method on a new trait or class well a new trait is necessary
usually a class is sufficient and you declare an implicit conversion
function from T to this new class and this implicit conversion function
is a PTV F using the same typeclass so in this way you automatically
extend your existing typeclass with new syntax you do not change a
type domain of your typeclass when you do this since you don't change
the domain you don't need to change the code of the existing typeclass
so this can be done in a different piece of code or a different library
different module and the implicit conversion function can be done
as an implicit class I will show you the code in a second and that
makes called shorter action here\textsf{'}s how it works suppose we implements
the monoid typeclass so this is our partial type 2 type function which
has some methods in the trait here is our syntax so this is this new
trait or class that we need to implement for the syntax purposes I
called an implicit class and it has one argument which is so it\textsf{'}s
implicit class is really a function that at the same time defines
a new type of this name and the function that creates values of this
type the function has this argument it also has an implicit argument
of the partial type 2 type per function which means that this is a
partial type to value function so like I said implicit class means
you define at once and you type and a function that creates a value
of this type with this argument so in this way it\textsf{'}s doing what I said
here to do in one step I define a new trailer class a new type and
I define a function that creates values of that type from values of
type T so here\textsf{'}s type M at the same time I constrain the type parameter
m to belong to the typeclass la nuit so now it\textsf{'}s a very short code
comparatively all I need to do now is to implement a method that I
want the method I want is the syntax method so let\textsf{'}s call it append
log I can change the name if I want because this is an extension so
I do not actually change the functionality of monoid as it was previously
defined I'm adding new syntax to the previous syntax the previous
index will still keep working and so I can have a new name if I wish
for the new syntax so this is the method that will be available on
108 types and the method will be append log with an argument Y I will
just use the combined method from the moon wind and there\textsf{'}s no new
functionality here I'm just repackaging the combined in the new syntax
so how does this work then here\textsf{'}s a data type in my application which
is log data as I mentioned before logging is a typical monoid example
because there isn't there\textsf{'}s an empty log and there\textsf{'}s appending to
log so you can put two logs together and it\textsf{'}s a bigger log again so
let\textsf{'}s define what empty log means is the string that says no log so
far and then let\textsf{'}s create a menorah instance which is a monoid of
type my log data I'm using implicit Val here why not so the combined
function will check if one of the logs is emptied and I just take
the other one if not empty I will concatenate logs and add a new line
between those log lines so this is a little more sophisticated than
just concatenating strings so my logs will be well formatted will
always be new lines separated then I import this monoid syntax now
this is the new thing that I defined here for syntax I import and
now here\textsf{'}s the code of my application I have some log values here
one log message another log message and then I just say initial log
a pen log log data wand a pen log log data - so I'm appending all
these logs so this is the new syntax but I have just defined and it
works the log result is equal to this string what I could do for instance
very easily now cuz I could rename the second log to {[}Music{]} plus
plus plus what happens then I have code like this so this might be
more readable depending on my application I am free to add new syntax
without changing the typeclass that was defined before so I'm completely
open to extension without having to change any of the library code
for Edmund okay so to summarize what we have gained is that the partial
function that we defined appears as emitted on values of the relevant
types and only on those types so the plus plus plus will be only defined
on those types that have a monoid instance in my previous example
and the new syntax is defined automatically on all the types I did
not have to define plus plus plus specifically for my log data not
like that at all I define it generally for any type M it has a monoid
instance so this is the power of typeclasses let\textsf{'}s now go through
some worked examples this is going over the entire material of this
tutorial the first example is that we want to define a partial type
value function of this kind the bit size has a type parameter T and
if that\textsf{'}s an int type it returns 32 and if it\textsf{'}s a long net return
64 otherwise this type the value function remains undefined how would
we implement that we go systematically so a partial type 2 value function
requires first of all the partial type 2 type function to define a
type domain so let us define this type constructor as a case class
we could not just use a type definition because that\textsf{'}s all going to
be int for all the types T and so that\textsf{'}s going to be a type collision
so let\textsf{'}s do a case class instead so this is a type constructor that
will be our personal type two type function now we want to define
this only for intent law so we do implicit Val bit-sized int evidence
has bit sized with value 34 and long evidence has bit sized with value
64 32 64 notice we put into the type that will be our type function
we put the information that this function needs that the function
we want is the bit size that will return to our 64 this information
is carried by this type so the f-type evidence value here is the information
we need that\textsf{'}s almost always going to be the case for any partial
type functions the partial type to type function represents a type
that carries all the information we'll need about the type that the
type 2 value functions we'll use later and the only information we're
required to return is this number so let\textsf{'}s put this number as our
type in here now we define the partial type 2 value function so bit
size has an implicit argument of type with size T and that returns
just this evidence value dot size that\textsf{'}s enough that\textsf{'}s all we need
to do and indeed this works as expected the test verifies that the
next example is to define the mono it instance for this type now notice
this is an option of a function from string to string so I'm going
to use that as a type and I'm going to use the cats library for the
standard memory typeclass so my tests here are all going to use the
law checking for the cats library that I implemented in a different
file so this is my data type I just define this as an option from
string to string since this is such a simple type no need to do case
classes here myself so defining a typeclass instance for the standard
typeclass in the library means that the type constructor that PT TF
is already defined in the library it is the monoid already defined
in the cat\textsf{'}s library the type constructor is there but I'm going to
add more types to the domain so that\textsf{'}s always going to be possible
adding north types to the domain of this portion function and this
so because the mono it is not sealed trait is just a trait not sealed
here and so I can always add new new instances or new types to the
type domain of that partial function so I'm going to so add this type
to the type domain in order to do this all I need to do is to create
value of the type monoid of data that\textsf{'}s all that is required now so
here\textsf{'}s one value I create on this type I need to override two functions
empty and combine the empty is a value of this type it combined is
a function from two values of this type to a third value of this type
so what is a naturally selected value of this type well I can think
of many one could be it\textsf{'}s an option of identity function so for some
identity function so that\textsf{'}s what I write here and the combined would
have to be such that if there is a non-empty option then I compose
these two functions so I have some of one function string to string
some of another function I can post these two functions so this is
the code I'm writing here so if there\textsf{'}s a sum and the sum and I compose
these two functions in all other cases I return none so clearly the
identity function here is a neutral element for this operation so
if I compose identity with anything I get the same function again
in all other cases I get none anyway so this will satisfy the laws
hopefully it\textsf{'}s kind of a little boring instance because it very often
produces none whenever one of the two parts of the combined one of
the two arguments of the combined function isn't none it will produce
no another instance would produce not much less frequently how would
that work well if one of the two arguments of the combined function
is none then I return the other one and so none becomes the neutral
element and then I do compose the functions if they have two functions
so basically I prefer to keep the function if I have one is non-empty
option I prefer to keep it unless both are empty then the result won't
be none so that\textsf{'}s perhaps a more interesting instance but we're free
to choose one or the other it\textsf{'}s not really clear at this point which
one would be more interesting so there could be different implementations
of the same typeclass and there could be use cases for both of them
because of this I don't make them implicit in my test code I want
to keep them explicitly implicitly be possible with only one of them
because I cannot have two positive values of the same type and I check
that both of these satisfy the monoid laws no the satisfying minora
Clause requires two implicit arguments of the arbitrary data and non-oil
instance so I since I'm not doing the implicit I have to put these
arguments by hand if I look at this function it has an arbitrary typeclass
and the monoid typeclass so I need to present arguments and the arbitrary
data I don't know where to get that but it\textsf{'}s implicitly available
so I just say possibly arbitrary data and that\textsf{'}s how it works both
are valid monoid instances it turns out the third example is by assuming
that a and B are types with monoi oil instance I define a monoid instance
for the product type so this is a interesting example because it shows
that I don't have to implement everything from scratch if there are
monoid instances for some previous types I can just define monoi instance
for a new type and don't have to write a lot of code maybe those monoid
instances for the previous types had a lot of code on them but this
code is not very large so how do I do that well I use this implicit
death mechanism which is I define a function that produces the type
evidence for the product type so the type evidence is the value of
a type monoid of product type so i produce this type evidence given
the type evidence for monoid a and one going to be so this is what
it means sure to define the noid instance for product a B if I have
monoid instances for a and B it means to make a function it takes
the two monoid instances I remind you that what noid instance is exactly
the same as a type evidence value it\textsf{'}s just for from annoyed so typeclass
instance is exactly the same as a type evidence value it\textsf{'}s a value
of the type that is the partial type two type function applied to
the type that were producing evidence for so if you want producing
evidence for type a and type evidence is something of type one noid
a and that\textsf{'}s something we'll typically carry the entire information
when to implement know it for type a so that is also called for that
reason monoid the monoid instance for type a and so our task is to
implement a function that takes monoid instances for types a and B
and produces a monoid instance for type product a B well so how do
we do that we'll just say we're all new monoid which is the way to
extend the trait very quickly and we override two methods so we need
to produce a value of type tuple a B and the evidence will give us
a value of type a and the value of type B so we just put them into
a tuple and the combine works in a similar way so we know how to combine
two A\textsf{'}s and we know how to combine two B\textsf{'}s so let\textsf{'}s shows us how to
combine a tuple a B and another tuple a B or just combine a separately
and you combine these separately and you use the evidence values to
fetch the combined functions from the one monoi oil and another monoid
so that\textsf{'}s all let\textsf{'}s test so this test is just going very slowly to
make it clear exactly what we're having achieved well we have achieved
so first we have no entered uh Balma lloyd instances in scope just
make sure we don't have them so this would not compile and this would
not compile now we declare these instances so for int let\textsf{'}s say the
empty value is 1 and combined is product that\textsf{'}s fine that works for
double-amputee is zero and combined as a sum that works to multiplication
actually wouldn't work because it\textsf{'}s not precise enough and it would
violate associativity by precision errors by by roundoff errors so
I use addition not multiplication for double alright so after I have
defined instances as implicit values of these types we have both int
and double monoid instance event scope in this will compile and work
whereas here it did not alright so now that should be sufficient for
us to be able to derive the Malloy instance for the tuple int double
automatically and that works so the monoid law has work that\textsf{'}s this
test runs and that\textsf{'}s how it works the next example is to show that
if a is a monoid and B is a semigroup then the disjunction a plus
B is a mohamed now to show this means again to write a function it
takes a type evidence for monoid of a in the type evidence for semi
group of b and produces the type evidence of monoid of a plus B were
using equivalent terminology typeclass instance for monoid of a typeclass
instance for B as a semi group these are two values these are going
to be arguments of my function and the result of my function must
be the typeclass instance from annoyed for type a a plus B just either
a B so showing this is not some kind of theoretical mathematical exercise
but it\textsf{'}s a specific coding exercise I need to write a function that
produces the evidence of monoid typeclass given these two evidences
and I want to check laws so here\textsf{'}s how it works this is this function
has two type parameters and two implicit arguments one is the evidence
that a E is a monoid and the other is the evidence that B is a semigroup
remind you the semigroup doesn't have the selected element mono it
has both a selected element and the binary operation a semigroup just
has the binary operation no select an element so it\textsf{'}s interesting
that if we combine the two of them with the disjunction and the result
can be monoid while in the previous example we had a product both
of them needed to be a monoid for the product okay I'm annoyed because
we need to produce the empty value so both of them must have an empty
value but here with disjunction we don't need to produce both empty
values just one is sufficient so that\textsf{'}s why one thing I'm annoyed
and another is the semigroup is sufficient alright so let\textsf{'}s see how
that works so empty element needs to be of type either a B well obviously
we don't have selected naturally selected element of B because it\textsf{'}s
a seven group we do have a naturally selected element of monoid so
we produce that okay now how does combine work all takes X of either
a B Y of either a B needs to produce again either either a B so we
have different situations we can have a and a we can combine a a obviously
because it\textsf{'}s a monoid b and b we can also combine b and b obviously
so these cases are easy another two cases when it\textsf{'}s not clear what
to do now we have a left of XA and the right of YB so how do we combine
now we can't really combine a and B we have no idea what these types
are except that one is a semigroup and another is a monoid but they're
not combined a ball directly one with the other so we have to ignore
one of them which one know we can think about this but basically things
don't work unless here you ignore the X and here you ignore the Y
and let\textsf{'}s check that this is correct first we don't have instances
then we define instances for int so let\textsf{'}s see we need something that\textsf{'}s
not a monoid that\textsf{'}s a semigroup it\textsf{'}s kind of hard to come up with
such such a thing most operations we know are monoidal like plus because
as neutral we needed an operation that does not have a neutral element
but is associative so it\textsf{'}s not easy well fortunately there is a paper
which I'm referring to here it describes a function that is non commutative
but associative and this function does not have an inverse and it
does not have a neutral element so I'm using this function which is
buttons function which is described in this article you find by this
formula very simple formula kind of curious in this not commutative
and yet associative in any case this is fine for a semigroup and for
the double I use the same instances before the addition with zero
and it works so if you change this to X instead of Y or here to whine
sin of X it was not work it will break so this is a curious definition
but that\textsf{'}s interesting we have only one choice to define annoying
instance on the disjunction so think about it option is a disjunction
so if you have a monoid an option a is a monoid an optional is also
a monoid disjunction of two monitors I'm annoyed because the second
group is less than a monoid so that\textsf{'}s good conjunction of two Mundo
videos I'm annoyed so you can combine Malloy\textsf{'}s quite easily and this
is a generic way of defining these combinations the next example is
to define a functor instance for this type now here were using try
which is a scholar standard library API just not a data type it\textsf{'}s
a special thing you find in the Scala library sequence is a another
thing you find in the Scala library so we're just trying to say how
can we do things with Scala library you find type constructors can
we make them into functors in terms of cats library let\textsf{'}s say yes
so we say here\textsf{'}s this type I use the type definition to define the
type function f so that F after this becomes a type function defined
like this and then and in order to define a functor instance I need
to define an implicit value of type factor of F so that\textsf{'}s why first
I define this name F like this is a type function and then I declare
the new factor instance by overriding the map now I just implement
the map so hard way implement the map well FA is this F of a which
is a sequence of trial of a I can map over a sequence the result will
be a try I can map over try and the result will be again a try so
this is a functor because it has a map this is also a function because
it hasn't helped composition of two funders is a factors because this
is a functor because I can just compose maps like this and all I'm
doing here is to make the cat\textsf{'}s library aware of this being a factor
so that\textsf{'}s all I need to do I'm not going to check laws here because
it\textsf{'}s quite a lot of work to produce arbitrary values of these types
especially they try but it is easy to verify that composition of two
functions is a factor so we could have checked the laws if we wanted
to the next example is to define a cats by functor instance for this
type function and notice that this type function has two type parameters
x and y and by functor is a typeclass defined in cats as a standard
by standard typeclass that is like functor except with two type parameters
it\textsf{'}s a factor with respect to both of them so to define that first
we define a type function or type constructor the name of that is
Q as we are given here and then I'm using either just to reduce typing
I don't want to declare my own sealed trait and two cases for the
disjunction but I could of course declare Q as a sealed trait with
two type parameters all be just more typing then all I need to do
is to define an implicit value of type by factor of Q so this is code
that does that to do that I need to override this function by map
so by map means that it\textsf{'}s a factor when you transform both type parameters
at the same time can that\textsf{'}s a factor so by factor means that it\textsf{'}s
a factor with respect to both type parameters at once so you transform
both of them at the same time and the result transforms as you will
expect so for instance either of a a be transformed with two functions
two arbitrary functions one a to C and the other B to D replaces this
with either CCD so that\textsf{'}s what is required now I'm not going to write
code for this function and we're just going to use my curry Howard
library to implement the code automatically using the type this is
possible and it works I'm just trying to reduce the time I'm spending
writing code now disk this is something we already know how to implement
functions given their types and this work can be done by the computer
so why not the non-trivial part here is how to define typeclass of
instances and that\textsf{'}s what we do by hand having done this we have defined
a simple set value and we check the by funky laws now the checking
the by funky laws is again a function I implemented in my test code
the next example is to define a country funkier typeclass so this
typeclass is like functor except it has contra f map where the direction
of the arrow visa counter to the direction of the transformation of
the function values the type constructor values since a contra factor
and the example consists of first defining a new typeclass having
this partial type 2 value function and then to define an instance
of this type laws for the type constructor of this formula which is
type argument a going to integer so this is a contra funky because
the type argument is to the left of the function here and we expect
to be able to define an instance instance of a country funky die class
for this type of structure so let\textsf{'}s see how that works so the given
country factor is this and let me define the type right away so after
this I have defined the type function C so first we need to define
a new typeclass which consists of a partial type two type function
carrying the data and we're required to carry this this type function
is contra functor with type variable which is the C now see here is
a parameter name it\textsf{'}s a little confusing perhaps let\textsf{'}s call this C
Bo just so that we don't confuse this with this C over here so this
is a contra factor this is a trait having a deaf method of the signature
we're required to help and in order to show that this type domain
includes this C we are required to produce a value of type control
factor of C so we do it like this so we we can either do a new country
factor or we can do an implicit object extends country factor is the
same thing could you do that it would be equalled we need to override
this function and this function is to have this type from FB to a
to a tend to be target again I let my curry Harvard library handle
this code and once I'm done it will work let\textsf{'}s do the same thing with
cats lightly cats library has a contractor typeclass which is called
contravariant and it has a different name and a different type of
the function instead of F myopic as my episode not a flipped argument
order other than that is very similar so how do I know this well I
just let me show you how I know this I just do that it\textsf{'}s not happy
because I need to define country map as it tells me so I press this
button here and I say implement methods tells me what methods I need
to implement now C of a is a - int as far as I remember and now I
can just say that\textsf{'}s my very hard lighting at work all right the title
notation which is required and then and then I define equality comparison
function for this scene it says it\textsf{'}s a function so C of int let\textsf{'}s
say is a function and comparing two functions is not immediate need
to substitute different arguments and compare results so that\textsf{'}s this
C equal code that says for all T C 1 of T must be equal to C 2 of
T and when the function C 1 is equal to C 2 so that I substitute into
the law checker and it will check my laws and that works tests lastly
the next example is to define a functor instance for the recursive
type we find by this formula so here let me first define this recursive
type so it\textsf{'}s the seal trade with three cases and the third case is
recursive it contains the same type of the trade itself all the cases
on the trait are parameterize by the type parameter a and extend cubed
so this is a functor because any always occurs to the right of the
error or here but this is the recursive instance so let\textsf{'}s find it
so let\textsf{'}s implement the functor instance with a new factor so functor'
is the cat\textsf{'}s functor just to check and needs to override the map let
me type override it\textsf{'}s not necessary to type all right but it\textsf{'}s more
checking this way if I mix up the type it was tell me that I'm not
overriding it in the right way so with these object oriented things
more checking has a better so type override make sure that it checks
that you are overriding it with the correct type okay so what does
this function do this function takes an FA of type QA it takes a function
f from A to B and it needs to produce K only so to do that we have
to match on this value let me rename this to Kiwi for clarity the
first case is the function from int to a well obviously I need to
compose this with a function f and then I will have a function from
int to be as required the second case doesn't have any age so it remains
unchanged just the type has type parameter is changed there was C
2 of a now it\textsf{'}s C 2 of B ok so this is option int I said option int
I'm not sure something is fishy here well X is int that\textsf{'}s true oh
I see it\textsf{'}s a case it does not tell me the type and it tells me something
else tells me that possible trying with your types so the interesting
case is the third case so the Q here is a key of a and I need to produce
key of B now I know how to produce key of B so I used a recursive
call to the same map that I'm defining and I call this one q + and
put this into c3 so in this case I remain in the c3 case and I transform
this Q by using the recursive definition of the same map so that\textsf{'}s
how I have to do it there\textsf{'}s no no other way really so in this way
we defined a functor instance so let\textsf{'}s see how I would check that
this function works correctly so for example I get this implicitly
founder Q dot map is the value that I just defined I could have said
Q functor instance dot map because I just defined it here but I don't
want to know about these names these names are completely unimportant
as long as you make them implicit so I'm going to use this as my data
and put identity function on it and see if that transforms the data
into the same form and it does so it\textsf{'}s just sanity check I'm going
to check the laws are more systematically in a second to do that I
need an equality comparison so that\textsf{'}s a bit involved because there
are many cases so I'm going to compare each case and then there\textsf{'}s
a recursive case as well and I need to compare functions so all of
that requires extra code so here is the case for comparing functions
here\textsf{'}s the recursive call so if I need to compare a c3 with c3 I recursively
compare their contents of c3 using the same C equal function so that\textsf{'}s
how this works this is just to see that this works this would fail
is that on the same and finally I call the frontal or checker on this
type using C equal and the tests pass the final worked example was
a bit more advanced so I started but it\textsf{'}s not so bad it\textsf{'}s to show
that you can define a functor instance for a disjunction if you have
functor instances for the two type constructors so this is a bit more
advanced because you need to define a type function that is a disjunction
of two given type functions so I need to define an implicit def which
would have to type arguments F and G each of them being type functions
and two implicit arguments which are the evidence that F is a factor
and that the G is a function but what am I going to return I'm going
to return if evidence that F plus G is a function but what is F plus
G F plus G is a new type constructor in other words a new type function
but it doesn't have a name yet and I cannot have a name for it because
F and G are my parameters so the only way I mean to express this is
to say that this is an anonymous type function so I'm returning type
evidence that an anonymous type function is of typeclass functor and
this is this anonymous type function it\textsf{'}s X going to either f of X
and G of X so that\textsf{'}s a type X is a type parameter this is type expression
that defines my type function and so the lambda syntax is syntax for
anonymous type functions using the kind projector plugin so that is
the kind of difficult part and other than that the school is quite
straightforward the difficult part is reasoning about these higher-order
type functions so for convenience I can put a name on it in the body
of this function but I cannot put a name on it before I define the
function return type so that\textsf{'}s why this kind projector is important
but other than that it\textsf{'}s not so bad so type either FG is a type function
that is the same as this anonymous type function over there it just
has a name now and that\textsf{'}s now easier to use I can just put this name
whenever I need it so now I return this functor instance by overriding
the map I have can either F G of a and I have a function from A to
B and I need to return either G only so how do I do that well I get
this FG a which is either F of T or F of a on G of a I'm matching
it if it\textsf{'}s F of a then I use the evidence for F to get the map of
F away with less transformation T and if it\textsf{'}s in the right I'll use
the evidence for G to get the map for the functor gene use that map
on the G value and the transformation T so that\textsf{'}s it that\textsf{'}s a very
straightforward code now I test this code I create filter instances
for some simple data types D 1 and D 2 very very simple data types
for these data types I can just implement functor instances like that
automatically and finally I I say well let\textsf{'}s call this d1 or d2 so
funny again for convenience introduced a specific name for the disjunction
of two factors so this d1 or d2 is now a new type function which has
a disjunction of the two type functions d1 and d2 and I check the
function laws for d1 or d2 now the implicit function here was called
invisibly I didn't have to call it myself to produce the type evidence
that this is a functor but you see this function requires that evidence
it wouldn't break even compiling if I didn't have that evidence since
it compiles them it\textsf{'}s correct now in this code I will show you how
I attempted to do this without the current projector it\textsf{'}s kind of
difficult and the problem is we need to define this name if we cannot
have anonymous functions anonymous type functions we have to define
this name somewhere but we cannot define it before we have the type
constructors F and G and so we have to define it inside the body of
the function and then we can define the instance like this and check
the laws but nobody outside of this function can see that instance
because this is a function this is not an object this is not a well
is this a function has to be called and when you call us it will define
the instance and check the laws for it which works but normally outside
of this code will be able to use this in instance so if you don't
use the kind projector then you can't really express this situation
but you actually have defined a functor instance for a disjunction
of two arbitrary factors given as type parameters and this functor
instance you see it\textsf{'}s usable outside of this code so I can put this
into a library I can put this into the companion objective factor
and nobody will have to do any imports or anything just we'll just
work automatically so that\textsf{'}s the power of implicit function definitions
that can automatically build new implicit evidence value so this is
this becomes a new impressive evidence value that is automatically
built up from existing implicit evidence values these two so this
concludes the worked examples and here are some exercises for you
that are quite similar to the worked examples and once you go through
these exercises you will really have a solid understanding of type
functions and typeclasses by way of conclusion let me summarize what
are the problems we can solve now we can define arbitrary partial
type two type functions and partial type two valued functions typeclasses
are just a way to systematically manage partial type two value functions
a lot different so just PTDS under student is somewhat more systematic
way we can define these together or separately we can define some
of them then later more partial type two values functions we can combine
them we can use a Katz library to define instances for some standard
typeclasses such as mono word semigroup functor and so on we can derive
typeclass instances automatically from previously derived ones or
previously programmed ones and we can reason about higher type functions
types and kinds whatever that is necessary so what is it that we cannot
do at this point no there\textsf{'}s still things we cannot do one of these
things is to derive typeclass instances automatically for polynomial
data types notice the case classes sealed traits with disjunction
in case classes with with data in them although that curry Howard
library can do this in some cases it cannot do this in all cases and
cannot do this automatically by implicit deaths either this requires
more advanced tools which are available in the shapeless library and
I have a link to a book online book a guide to shapeless where it
is explained in depth how automatically an automatic derivation of
type last instances works in the shapeless library another thing we
cannot do is to derive a recursive type generically from an arbitrary
type function so we have just seen an example of defining a functor
instance for recursive type but this type was defined by hand so suppose
we have a type function f given as a parameter and we want to define
a recursive type R via this equation this is a recursive type equation
or also called a fixed point equation R is a fixed point of the function
f so this fixed point is a function of F and that function is usually
denoted by Y the so called Y Combinator it takes an F which is itself
a function and it returns its fixed point so the y must be defined
by type equation of this sort so Y of F must be equal to Y of F is
that R which is equal to F of R so Y of F must be equal to F of Y
of F but this doesn't compile Scala doesn't allow us to make things
like this more work is necessary to even define such things or have
a generic type function that computes the recursive type and we haven't
seen how to do it also for such recursive types we cannot derive typeclass
instances automatically so for instance if F were a functor with some
other type parameter then R would also be a factor or if if F is a
mono then I would also be able know either something like this we
would like to derive automatically typeclass instances whenever they
exist and we cannot do this with the tools we have seen here now there
are some advanced libraries like matryoshka that implement type level
recursion or type level fix points that are able to handle these problems
giving you a link here also shapeless might help not sure in any case
these are more advanced topics which are perhaps further away from
practical applications than I would like and there are some interesting
discussions there is a blog post very interesting series of explanations
of this kind of stuff that I encourage you to look at if you're interested
this concludes chapter 5 
\end{comment}

